Skip to content

Commit b6c623e

Browse files
committed
docs: add API response validation example to basic usage
1 parent 207205c commit b6c623e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

README.md

+26
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,32 @@ type User = z.infer<typeof User>;
661661
// { username: string }
662662
```
663663

664+
Validating an API response:
665+
666+
```ts
667+
import { z } from "zod";
668+
669+
const userSchema = z.object({
670+
id: z.number(),
671+
username: z.string(),
672+
email: z.string().email(),
673+
});
674+
675+
type User = z.infer<typeof userSchema>;
676+
677+
async function getUserById(id: number) {
678+
const response = await fetch(`/api/users/${id}`);
679+
// data is untyped JSON response from the API
680+
const data = await response.json();
681+
682+
// parse and validate the data against the schema to ensure it matches the expected shape
683+
const user = userSchema.parse(data);
684+
685+
// user is now fully typed as { id: number, username: string, email: string }
686+
return user;
687+
}
688+
```
689+
664690
## Primitives
665691

666692
```ts

0 commit comments

Comments
 (0)