Skip to content

Commit d8d20a6

Browse files
committed
docs: add API response validation example to basic usage
1 parent 700d9f4 commit d8d20a6

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

README.md

+24
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,30 @@ type User = z.infer<typeof User>;
708708
// User: { username: string }
709709
```
710710

711+
Validating an API response:
712+
713+
```ts
714+
import { z } from "zod";
715+
716+
const userSchema = z.object({
717+
id: z.number(),
718+
username: z.string(),
719+
email: z.string().email(),
720+
});
721+
722+
type User = z.infer<typeof userSchema>;
723+
724+
async function getUserById(id: number) {
725+
const response = await fetch(`/api/users/${id}`);
726+
// data is untyped JSON response from the API
727+
const data = await response.json();
728+
729+
// parse and validate the data against the schema to ensure it matches the expected shape
730+
const user = userSchema.parse(data);
731+
732+
// user is now fully typed as { id: number, username: string, email: string }
733+
return user;
734+
}
711735
```
712736

713737
## Primitives

0 commit comments

Comments
 (0)