Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There is no single reliable command that turns an arbitrary JSON API into a complete Zod contract. If the API publishes JSON Schema, Zod offers a reverse converter, but it is experimental. If you have only response examples, use them to draft a candidate schema and verify it against the endpoint’s documented behavior and multiple real responses. In a Zod-first codebase, define the runtime schema once and derive its TypeScript type with z.infer.

Choose a generation route based on what the API provides

Starting point Route What to watch for
JSON Schema contract Try z.fromJSONSchema(jsonSchema) Zod documents this reverse conversion as experimental and outside its stable API. Check that the contract’s constructs are supported before relying on it in production.
One or more example response bodies Draft a Zod schema from the examples, or use a sample-based generator to propose one; then compare it with more responses and endpoint documentation. An example demonstrates an observed payload, not every valid response. The reviewed documentation does not establish a particular sample-to-Zod generator as best-in-class or officially endorsed.
Existing Zod schema Use it for runtime validation and derive the static type with z.infer<typeof Schema>. If the schema coerces or transforms values, distinguish the accepted input from the parsed output with z.input and z.output.
Zod schema that must be published as JSON Schema Use z.toJSONSchema(schema) and choose the target dialect required by consumers. The default target is Draft 2020-12. Draft 7, Draft 4, and OpenAPI 3.0 Schema Object targets are also documented; some Zod types cannot be represented.
Zod schema to include in an OpenAPI description Consider zod-to-openapi, registering the schemas and paths needed for the API description. Follow the library’s setup and version-compatibility guidance, particularly when using extension behavior or registered schemas.

Build a Zod schema and TypeScript type from a response

For an API without a published schema, begin with the response shape you actually receive. Treat it as a draft, not proof that the endpoint always returns exactly that shape. Confirm optional properties, nullability, arrays, error payloads, pagination, and version-specific variants against endpoint documentation and additional responses.

Define the wire-response schema

import * as z from "zod";

const UserResponse = z.object({
  id: z.string(),
  name: z.string(),
  email: z.email(),
  // Add optional or nullable cases only when the API contract supports them.
});

type UserResponse = z.infer<typeof UserResponse>;

const response = await fetch("/api/user/123");
const body: unknown = await response.json();
const user = UserResponse.parse(body);

The schema validates the value at runtime; the inferred type gives TypeScript the corresponding static shape. Keeping both tied to one definition avoids maintaining a separate handwritten type that can drift from the validation rules.

Check input and output when parsing changes values

A response schema should make clear whether it describes the JSON received from the server or a value after application-side coercion or transformation. When those differ, use z.input<typeof Schema> for the accepted input type and z.output<typeof Schema> for the parsed result. For example, a schema that transforms a string into a number accepts a string but produces a number; z.infer corresponds to the output type.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert an existing JSON Schema contract into Zod carefully

Zod’s z.fromJSONSchema(jsonSchema) converts in the JSON Schema-to-Zod direction, but Zod marks this function experimental and not part of its stable API. Before adopting it, inspect the source contract for constructs the converter supports, run representative contract cases through the generated schema, and plan for compatibility changes associated with an experimental API.

Conversion should not be assumed to preserve every behavior in either direction. Zod’s documentation identifies types such as bigint, symbol, undefined, void, date, map, set, transforms, custom schemas, and some special number cases as unrepresentable in JSON Schema by default. If a schema uses these, determine how the converter’s unrepresentable-type options apply rather than assuming a faithful portable equivalent.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Export JSON Schema or OpenAPI from Zod

Generate JSON Schema for a chosen dialect

For Zod-to-JSON-Schema conversion, use z.toJSONSchema(schema). Its default output targets JSON Schema Draft 2020-12; the documented alternatives include Draft 7, Draft 4, and OpenAPI 3.0 Schema Object. Select the target based on what the receiving tool accepts instead of assuming all JSON Schema dialects are interchangeable.

By default, the generated JSON Schema represents the Zod schema’s output type. If the consumer specifically needs the input side of a schema whose input and output differ, select io: "input". This distinction matters for transforms and coercions: a contract intended to describe wire data may need to describe what enters the schema, not the application value after parsing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Produce an OpenAPI description

For OpenAPI output from Zod, zod-to-openapi is an option. Follow its documented setup and compatibility notes, and register the paths and schemas that belong in the API description. A generated schema alone is not a complete endpoint contract: the description also needs the relevant operations and response structure.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate generated schemas against the endpoint, not just one example

Before using a generated or hand-drafted schema as an API boundary, compare it with the endpoint’s documented contract and varied responses. A single successful payload cannot establish how omitted fields, explicit null values, errors, pagination, or future API versions behave.

  • Check multiple responses, including records with different optional-field combinations.
  • Confirm whether a missing property and a property set to null are both valid; they are distinct cases.
  • Inspect error responses as well as successful responses if the same client code will parse them.
  • Check paginated or variant response envelopes and any version-specific fields.
  • Run contract examples through the resulting schema and review failures against the API’s documented behavior.

Only encode optionality, nullability, or unions when the API contract or observed response set supports them. Overly narrow schemas reject valid responses; overly permissive schemas provide little protection against unexpected payloads.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.