From 84e95261a49ad589d0b6befaae19c62c7249a055 Mon Sep 17 00:00:00 2001 From: Braden Wong <13159333+braden-w@users.noreply.github.com> Date: Fri, 6 Dec 2024 15:52:02 -0500 Subject: [PATCH] docs: add API response validation example to basic usage --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 124fefd87..ee9299327 100644 --- a/README.md +++ b/README.md @@ -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