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 207205c commit b6c623e
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,32 @@ type User = z.infer<typeof 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

```ts
Expand Down

0 comments on commit b6c623e

Please sign in to comment.