From d8d20a65aa1f8b0678134a514e4fc9847c5e5654 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 8efd44051..a358b89a0 100644 --- a/README.md +++ b/README.md @@ -708,6 +708,30 @@ type User = z.infer; // 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; + +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