Skip to content

Commit 84e9526

Browse files
committed
docs: add API response validation example to basic usage
1 parent 3020638 commit 84e9526

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
@@ -675,6 +675,30 @@ type User = z.infer<typeof User>;
675675
// User: { username: string }
676676
```
677677

678+
Validating an API response:
679+
680+
```ts
681+
import { z } from "zod";
682+
683+
const userSchema = z.object({
684+
id: z.number(),
685+
username: z.string(),
686+
email: z.string().email(),
687+
});
688+
689+
type User = z.infer<typeof userSchema>;
690+
691+
async function getUserById(id: number) {
692+
const response = await fetch(`/api/users/${id}`);
693+
// data is untyped JSON response from the API
694+
const data = await response.json();
695+
696+
// parse and validate the data against the schema to ensure it matches the expected shape
697+
const user = userSchema.parse(data);
698+
699+
// user is now fully typed as { id: number, username: string, email: string }
700+
return user;
701+
}
678702
```
679703

680704
## Primitives

0 commit comments

Comments
 (0)