Skip to content

Commit

Permalink
docs: add API response validation example to basic usage
Browse files Browse the repository at this point in the history
  • Loading branch information
braden-w committed Dec 6, 2024
1 parent 3020638 commit 84e9526
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,30 @@ type User = z.infer<typeof User>;
// User: { username: string }
```

Validating an API response:

```ts
import { z } from "zod";

const userSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string().email(),
});

type User = z.infer<typeof userSchema>;

async function getUserById(id: number) {
const response = await fetch(`/api/users/${id}`);
// data is untyped JSON response from the API
const data = await response.json();

// parse and validate the data against the schema to ensure it matches the expected shape
const user = userSchema.parse(data);

// user is now fully typed as { id: number, username: string, email: string }
return user;
}
```

## Primitives
Expand Down

0 comments on commit 84e9526

Please sign in to comment.