How to Validate API Responses in TypeScript With Zod Schemas

TypeScript types disappear at runtime. Learn how Zod schemas check real API data, how parse and safeParse differ, and how to build a schema from sample JSON.

Updated September 29, 2026 6 min read

Use the free JSON to Zod SchemaGenerate a Zod validation schema and TypeScript type from JSON

Your TypeScript front end declares interface Order { total: number }, the code compiles, and yet in production a page shows NaN because the API started sending "total": "19.90" as a string. Nothing warned you, because TypeScript types exist only at compile time. The moment data crosses a network boundary, the compiler's promises are just assumptions.

Zod closes that gap. You describe the expected shape once as a schema, Zod checks real data against it at runtime, and TypeScript derives the static type from the same schema. This guide explains how that works, how to handle validation failures, and how to generate a starting schema from a sample response instead of writing it field by field.

Why TypeScript alone cannot validate data

When TypeScript compiles to JavaScript, every interface and type annotation is removed. A line such as const order = (await res.json()) as Order is a statement of trust, not a check: if the server sends something else, the value flows through your app with the wrong shape until it breaks far away from the cause.

A runtime validator reads the actual value and compares it with a description of what is allowed. Zod is one popular option in the TypeScript ecosystem. Its main advantage is that the schema is the type definition: z.infer<typeof Schema> produces the TypeScript type, so the two can never drift apart.

The core Zod building blocks

Schema Accepts
z.string() any string
z.string().email() / .url() / .uuid() strings in that format
z.number() / z.number().int() numbers / whole numbers only
z.boolean() true or false
z.object({ ... }) an object with those keys
z.array(schema) an array whose items match schema
.optional() the key may be missing (undefined)
.nullable() the value may be null

Two distinctions trip people up. Optional is not nullable: .optional() allows a missing key, .nullable() allows an explicit null, and an API that does both needs .nullish(). And objects are not strict by default: z.object() strips unknown keys from the result without complaining. Add .strict() if an unexpected key should be an error, or .passthrough() to keep extra keys.

Generate a Zod schema from sample JSON

Writing schemas for a large response by hand is slow. The JSON to Zod Schema tool infers one from a sample in your browser.

  1. Open JSON to Zod Schema. Paste a real response into JSON sample, use Open file, or click Load sample.
  2. Set Root type name, for example Order. The exported schema becomes OrderSchema.
  3. Keep Detect email, URL, UUID & dates on to add .email(), .url(), .uuid(), .date() or .datetime({ offset: true }) when every sample value matches that format.
  4. Turn on .strict() objects if you want unknown keys to fail validation.
  5. Leave Export z.infer types on to get a type Order = z.infer<typeof OrderSchema> line for each object.
  6. Copy the Zod schema or Download it as a .ts file.

The generator creates one schema per object shape, reuses it wherever the same shape appears, marks keys that are missing from some array items as .optional(), marks values that were null as .nullable(), and uses z.number().int() for whole numbers. The output ends with a usage comment showing the parse call.

Using the schema: parse vs safeParse

parse returns typed data or throws a ZodError. safeParse never throws; it returns an object you can branch on:

import { z } from "zod";

const OrderSchema = z.object({
  orderId: z.string(),
  total: z.number(),
  items: z.number().int(),
  coupon: z.string().optional(),
});
type Order = z.infer<typeof OrderSchema>;

const payload = { orderId: "A-102", total: "19.90", items: 2 };
const result = OrderSchema.safeParse(payload);

if (!result.success) {
  console.log(result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`));
  // [ 'total: Expected number, received string' ]
} else {
  const order: Order = result.data;
}

The path on each issue tells you exactly which field failed, even deep inside nested arrays, which makes Zod errors far easier to act on than a TypeError three components later.

Use parse where invalid data is truly exceptional and an error boundary or request handler will catch it. Use safeParse where you want to show a message, log the problem and fall back to a default.

If an API legitimately sends numbers as strings, do not loosen the schema to z.string(). Convert on the way in:

const LenientOrder = OrderSchema.extend({ total: z.coerce.number() });
LenientOrder.parse(payload); // { orderId: "A-102", total: 19.9, items: 2 }

Other ways to get runtime validation

  • Write the schema by hand. For small objects this is fine and lets you add business rules (.min(1), .max(100)) from the start.
  • JSON Schema plus a validator. If other languages need the same contract, a JSON Schema document is language-neutral. The JSON Schema Generator can draft one, and our guide on creating a JSON Schema from sample data explains the trade-offs.
  • Types only. If the data comes from your own backend in the same repository, sharing types may be enough. Tools like JSON to TypeScript generate interfaces, but remember they add no runtime check.
  • Other schema libraries. Valibot, Yup, ArkType and similar libraries solve the same problem with different APIs and bundle-size trade-offs.

Tips and common pitfalls

A sample is not a contract

A generator can only describe what it sees. A field that is always present in your sample becomes required, even if the API documentation says it is optional. Paste several responses as a JSON array to capture more variation, then compare the result with the documentation.

Replace z.null() fields

If a key is null in every sample, the tool writes z.null() because it has no other information. Change it to the real type followed by .nullable(), for example z.string().url().nullable().

Format detection can be too strict

An .email() or .url() rule inferred from five samples may reject valid values the API sends later, such as a relative URL. Keep format checks only where the API guarantees the format.

Check your Zod version

The generated code uses the long-standing method style, such as z.string().email(). Newer Zod releases also offer top-level helpers like z.email(); check the Zod documentation for the version you install.

Validate at the boundary, once

Parse data where it enters your app (the fetch wrapper, the API route, the message consumer) and pass the typed result inward. Validating the same object in every component costs time and adds noise.

If the sample itself will not parse, fix it with the JSON Validator first.

Frequently asked questions

What is the difference between parse and safeParse in Zod?

parse returns the validated data or throws a ZodError. safeParse returns { success: true, data } or { success: false, error }, so you can handle failures without try/catch.

Does Zod remove unknown keys?

Yes. By default z.object() strips keys that are not in the schema from the parsed result. Use .strict() to reject them or .passthrough() to keep them.

How do I get a TypeScript type from a Zod schema?

Use type Order = z.infer<typeof OrderSchema>. The type updates automatically whenever you change the schema.

What is the difference between optional and nullable in Zod?

.optional() allows the key to be missing or undefined; .nullable() allows the value null. Use .nullish() when both are possible.

Does validation slow down my app?

For typical API responses the cost is small compared with the network request. Very large arrays can add measurable time, so validate them once at the boundary rather than repeatedly.

Try it now: JSON to Zod Schema

Loading tool…