Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Generate Zod Schemas and TypeScript Types from JSON APIs

Choose a Zod generation path based on whether your API provides JSON Schema, sample responses, or an existing Zod definition—and account for conversion limits.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

There is no single reliable command that turns any JSON API into a complete, production-ready Zod contract. The right approach depends on what you have: an API-published JSON Schema can be converted with Zod’s experimental z.fromJSONSchema(); an existing Zod schema can supply both runtime validation and a TypeScript type; and sample responses can help you draft a schema, but must be checked against the API’s documented variations.

Choose a generation route based on what the API provides

Starting point Practical route Key qualification
The API publishes a JSON Schema contract Try Zod’s z.fromJSONSchema(jsonSchema). This reverse conversion is experimental and outside Zod’s stable API. Verify support for the contract’s constructs before depending on it in production. Zod JSON Schema documentation
You have representative JSON response bodies, but no schema Draft a Zod object schema or use a sample-based generator to create a candidate, then compare it with multiple responses and endpoint documentation. A sample shows only an observed payload. The reviewed sources do not establish a best-in-class sample-to-Zod generator or endorse a specific one.
Your TypeScript project already defines Zod schemas Use the schema for runtime validation and derive a static type with z.infer<typeof Schema>. When parsing transforms input, z.input describes the accepted input and z.output the parsed result. Zod basics documentation
You want to publish JSON Schema from Zod Use z.toJSONSchema(schema) and select a target dialect appropriate for downstream consumers. The default is Draft 2020-12. Draft 7, Draft 4, and OpenAPI 3.0 Schema Object targets are also listed; some Zod types cannot be represented and throw by default. Zod JSON Schema documentation
You want to publish OpenAPI from Zod Consider zod-to-openapi, registering the schemas and paths needed for the API description. Follow the library’s setup and version compatibility notes, particularly for extension behavior and registered schemas. zod-to-openapi documentation

Define one Zod schema for validation and its TypeScript type

For a Zod-first codebase, make the schema the shared source of truth. The schema validates data at runtime; z.infer derives a compile-time type from that same definition.

As an Amazon Associate I earn from qualifying purchases.

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);

Using unknown for the decoded body makes the boundary explicit: the server’s response is not treated as a trusted UserResponse until parsing succeeds. A successful parse returns validated data; an invalid payload causes a Zod error.

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

Keep wire input and parsed output distinct when needed

A schema can transform a value while parsing. In that case, the JSON accepted from the server and the value your application receives may have different types. Use z.input<typeof Schema> for the schema’s accepted input and z.output<typeof Schema> for its parsed output. For response validation, be explicit about whether the schema describes the JSON on the wire or the value after transformation. Zod documents input and output types.

Use sample responses as evidence, not as the whole contract

A sample-to-schema generator can only infer from the examples it sees. One successful response cannot establish whether a field is always present, sometimes omitted, nullable, or different across endpoint variants. It also does not specify error payloads, pagination, or changes between API versions. Treat generated output as a draft, then reconcile it with the endpoint documentation and multiple real responses.

  • Check more than one response, including meaningful variations and edge cases.
  • Decide from the API contract whether each field is required, optional, or nullable; do not infer those rules from a single example.
  • Model success and error responses, pagination, and endpoint variants where the API exposes them.
  • Validate the response at the network boundary so an unexpected payload does not silently enter the application as a trusted TypeScript type.

Convert between Zod and JSON Schema carefully

From JSON Schema to Zod

Zod documents z.fromJSONSchema() for converting in this direction, but labels it experimental and outside the stable API. Before adopting it, check that the JSON Schema features used by the API contract are supported and verify the converted schema against actual payloads. See Zod’s conversion documentation.

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

From Zod to JSON Schema

Zod’s z.toJSONSchema() generates JSON Schema from a Zod schema. Its default target is Draft 2020-12; the documented alternatives include Draft 7, Draft 4, and the OpenAPI 3.0 Schema Object format. By default, the generated JSON Schema represents the schema’s output type; use io: "input" when you need the input type instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Conversion is not lossless for every Zod construct. Zod’s documentation lists bigint, symbol, undefined, void, date, map, set, transforms, custom schemas, and some special number cases as unrepresentable by default. The converter has an unrepresentable option, but downstream JSON Schema consumers still need a representation they can understand. Check the documented behavior before publishing the result as a portable contract. Zod JSON Schema documentation

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

Generate OpenAPI when the goal is API documentation

If the goal is to describe API paths and request or response schemas in OpenAPI, rather than only validate responses in application code, zod-to-openapi is one option for producing an OpenAPI description from Zod. Follow its documentation for setup, schema registration, and compatibility with your Zod version. Library documentation and examples

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.