From b6c623eded279acbcc5e515b323a407531ef62d0 Mon Sep 17 00:00:00 2001 From: Braden Wong <13159333+braden-w@users.noreply.github.com> Date: Fri, 6 Dec 2024 16:12:54 -0500 Subject: [PATCH] docs: add API response validation example to basic usage --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index a3c888695..e92c4464c 100644 --- a/README.md +++ b/README.md @@ -661,6 +661,32 @@ type User = z.infer; // { 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 ```ts