Skip to content

Zod Tutorial for Beginners: Validate API Data in TypeScript

Learn Zod step by step: write a schema, validate API responses with safeParse, get TypeScript types with z.infer, and handle optional fields, enums, arrays and custom rules.

7 min readBy Admin

Zod Tutorial for Beginners: Validate API Data in TypeScript

Short answer: Zod lets you describe the shape of your data once, check real data against it at runtime with parse() or safeParse(), and get the matching TypeScript type for free with z.infer. This tutorial walks through every piece you need to validate API responses. If you already have a JSON sample, our free JSON to Zod tool writes the first schema for you.

All code below was run against Zod 3.25. Zod 4 is now the current major version (see zod.dev); the basics shown here work the same in both, and the few places that differ are called out.

Why use Zod instead of a TypeScript interface?

A TypeScript interface only exists while you compile. When your code runs, const user = await res.json() as User trusts the server completely: if age arrives as the string "29", nothing stops it. Zod checks the data when it arrives, so bad input fails at the edge of your app with a clear error instead of breaking something three functions later.

TypeScript interfaceZod schema
Checks data at runtimeNoYes
Gives you a static typeYesYes, via z.infer
Can express rules (min length, email, ranges)NoYes
Adds a dependencyNoYes (one package, no dependencies of its own)

Use interfaces for data you create yourself. Use Zod for data you receive: API responses, form input, environment variables, files and webhooks.

Step 1: Install Zod

# Zod 3 (what this tutorial was tested on)
npm install zod@3

# or the current major version
npm install zod

Zod needs TypeScript's "strict": true in tsconfig.json for its types to work properly. Then import it with import { z } from "zod".

Step 2: Define a schema and infer its type

import { z } from "zod";

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

type User = z.infer<typeof UserSchema>;
// { id: number; name: string; email: string }

z.infer reads the schema and produces the type, so the two can never drift apart. Change the schema and the type changes with it.

Zod 4 difference: z.string().email() still works but is deprecated there in favor of the shorter z.email().

Step 3: safeParse vs parse

parse() returns the data or throws a ZodError. safeParse() never throws; it returns an object you check with success:

const result = UserSchema.safeParse({ id: 1, name: "Jane" });

if (!result.success) {
  console.log(result.error.issues);
  // [{ path: ["email"], message: "Required", ... }]
} else {
  result.data; // typed as User
}

Use safeParse for user input and API responses, where failure is expected and you want to show or log a message. Use parse when invalid data is a bug and throwing is the right reaction, for example when reading config at startup.

Error text differs by version. Zod 3 says "Required" for the missing email above; Zod 4 says "Invalid input: expected string, received undefined". Read error.issues (it works in both); the old error.errors alias was removed in Zod 4.

Optional, nullable and default values

const ProfileSchema = z.object({
  nickname: z.string().optional(),   // may be missing (undefined)
  bio: z.string().nullable(),        // must be present, may be null
  middleName: z.string().nullish(),  // missing, undefined or null
  role: z.string().default("user"),  // filled in when missing
});

ProfileSchema.parse({ bio: null });
// { bio: null, role: "user" }

ProfileSchema.safeParse({}).success; // false: bio is required

The common mistake is using .nullable() when the API simply leaves the field out. Look at real responses: missing key means .optional(), "bio": null means .nullable().

Enums, arrays and nested objects

const Status = z.enum(["active", "pending", "banned"]);
Status.parse("active");             // "active"
Status.safeParse("deleted").success; // false

const OrderSchema = z.object({
  id: z.string(),
  status: Status,
  items: z.array(
    z.object({
      sku: z.string(),
      qty: z.number().int().positive(),
    })
  ).min(1),
  shipping: z.object({
    city: z.string(),
    zip: z.string().regex(/^\d{5}$/),
  }),
});

Errors in nested data come back with a full path. An order with qty: 0 and a four-digit ZIP gives two issues, at ["items", 0, "qty"] and ["shipping", "zip"], so you can point the user to the exact field.

Custom rules with refine

When a rule depends on more than one field, add .refine() to the object. The path option attaches the error to a specific field:

const SignupSchema = z
  .object({
    password: z.string().min(12),
    confirm: z.string(),
  })
  .refine((d) => d.password === d.confirm, {
    message: "Passwords do not match",
    path: ["confirm"],
  });

In Zod 4 the message option still works but is deprecated in favor of error.

Unknown keys and type coercion

  • By default z.object() strips keys it does not know, so extra fields vanish from result.data.
  • .strict() rejects unknown keys with an unrecognized_keys issue; .passthrough() keeps them. Zod 4 prefers z.strictObject() and z.looseObject() but keeps both methods.
  • z.coerce.number() turns "42" into 42, and z.coerce.date() turns an ISO string into a Date. Useful for query strings and form fields, which are always strings.

A real API response example

Here is a full example against the free JSONPlaceholder test API. The schema mirrors one post object, and the response is validated before anything else touches it:

import { z } from "zod";

const PostSchema = z.object({
  userId: z.number().int(),
  id: z.number().int(),
  title: z.string(),
  body: z.string(),
});
type Post = z.infer<typeof PostSchema>;

async function getPosts(): Promise<Post[]> {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);

  const result = z.array(PostSchema).safeParse(await res.json());
  if (!result.success) {
    console.error(result.error.issues);
    throw new Error("Unexpected API response");
  }
  return result.data; // Post[], checked at runtime
}

Writing that schema by hand is fine for four fields. For a response with forty, paste one real response into the JSON to Zod schema tool. It builds the schema in your browser, merges every element of an array (keys missing from some objects become .optional(), null values become .nullable()), and can detect email, UUID, URL and date strings, add .int() and .strict(), and export the z.infer type. An optional AI refinement step sends the JSON to our AI provider to suggest tighter rules; review those before you use them. If you only need the type and no runtime check, JSON to TypeScript generates interfaces instead.

A schema generated from one sample only knows that sample. If a field can be null or missing in other responses, loosen it by hand.

Common Zod mistakes

  1. Forgetting that parse throws. Wrap it in try/catch or switch to safeParse.
  2. Validating and then using the original object. Use result.data: it is the cleaned, typed copy.
  3. Making every field required because the sample had it. Real APIs omit fields; check the docs.
  4. Using z.any() to silence errors. It turns validation off for that field; prefer z.unknown() and narrow it later.

FAQ

What is z.infer in Zod?

z.infer is a TypeScript helper that extracts the static type from a schema. You define the shape once and get both the runtime check and the type.

What is the difference between parse and safeParse?

parse returns the data or throws a ZodError. safeParse returns { success: true, data } or { success: false, error } and never throws.

Should I learn Zod 3 or Zod 4?

New projects get Zod 4 from npm install zod. Everything in this tutorial runs on both; in Zod 4, prefer z.email(), the error option and error.issues. The Zod 4 migration guide lists the rest.

Can I convert JSON Schema to Zod, or Zod to JSON Schema?

Zod 4 has a built-in z.toJSONSchema() for the Zod-to-JSON-Schema direction; in Zod 3 the community package zod-to-json-schema does it. Going from a plain JSON sample to Zod is what our JSON to Zod generator does.

Is Zod only for TypeScript?

No. It works in plain JavaScript as a runtime validator; you just do not get the inferred types.

Start with one schema for the API response that causes you the most trouble. If you have a sample handy, generate the first draft with the free JSON to Zod tool and tighten it using the rules above.

Related Articles

Try Our Smart Tools

Put what you've learned into practice with our free AI, SEO and developer tools.