npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@saunos/openapi-to-zod

v0.11.0

Published

Generate Zod schemas from an OpenAPI spec

Readme

@saunos/openapi-to-zod

Generate TypeScript source that exports Zod 4 schemas from an OpenAPI 3.x document or a standalone JSON Schema.

Install

npm install @saunos/openapi-to-zod
# or
bun add @saunos/openapi-to-zod

CLI usage

Run directly with npx — no install needed:

npx openapi-to-zod https://example.com/openapi.json schemas.ts

Or from a local file:

npx openapi-to-zod ./openapi.json ./generated/schemas.ts

Run npx openapi-to-zod --help for the full option reference.

CLI options

| Flag | Description | | ----------------------------------- | ------------------------------------------------------------------------------ | | --mini | Emit zod/mini-compatible code (see Zod Mini) | | --json-schema | Treat input as a standalone JSON Schema document (with $defs) | | --use-date-codecs | Emit z.codec(...) for date / date-time formats, converting to Date | | --alphabetical | Sort object property keys and enum values alphabetically | | --no-strict | Collect all error-level diagnostics instead of throwing on the first | | --no-strict-additional-properties | Don't append .strict() for additionalProperties: false | | --no-default-non-nullable | Emit .optional() for non-required properties even when they have a default | | --override pointer=expr | Replace the auto-generated expression at a JSON Pointer (repeatable) |

Library API

generateZodSourceFromOpenApi

import { generateZodSourceFromOpenApi } from '@saunos/openapi-to-zod';

const res = await fetch('https://example.com/openapi.json');
const openApiObject = await res.json();

const { code, diagnostics } = await generateZodSourceFromOpenApi(openApiObject, {
  strict: true,
});

await Bun.write('./schemas.ts', code);

generateZodSourceFromJsonSchema

For standalone JSON Schema documents that use $defs for named sub-schemas:

import { generateZodSourceFromJsonSchema } from '@saunos/openapi-to-zod';
import schema from './my-schema.json';

const { code, diagnostics } = generateZodSourceFromJsonSchema(schema);
await Bun.write('./schemas.ts', code);

convertJsonSchemaToZod

For converting a single JSON Schema node to a Zod expression string (no full document, no $ref resolution):

import { convertJsonSchemaToZod } from '@saunos/openapi-to-zod';

const { expression } = convertJsonSchemaToZod({
  type: 'object',
  required: ['id', 'name'],
  properties: {
    id: { type: 'string', format: 'uuid' },
    name: { type: 'string' },
    age: { type: 'integer', minimum: 0 },
    tags: { type: 'array', items: { type: 'string' } },
  },
});

console.log(expression);
// z.object({
//   id: z.uuid(),
//   name: z.string(),
//   age: z.int().min(0).optional(),
//   tags: z.array(z.string()).optional(),
// })

Note: $ref pointers to #/components/schemas/* are not resolved by this function — use generateZodSourceFromOpenApi for schemas with cross-references.

Zod Mini

Pass useZodMini: true (or --mini on the CLI) to emit tree-shakable zod/mini-compatible code. The functional API is used instead of method chains:

| Regular Zod | Zod Mini | | ----------------------------- | --------------------------------------------------- | | import { z } from 'zod' | import * as z from 'zod/mini' | | z.string().min(1).max(50) | z.string().check(z.minLength(1), z.maxLength(50)) | | z.number().min(0).max(5) | z.number().check(z.gte(0), z.lte(5)) | | z.int().min(1) | z.int().check(z.gte(1)) | | z.array(x).min(1) | z.array(x).check(z.minLength(1)) | | schema.optional() | z.optional(schema) | | schema.nullable() | z.nullable(schema) | | schema.default(v) | z._default(schema, v) | | z.object(shape).strict() | z.strictObject(shape) | | z.object(shape).catchall(s) | z.catchall(z.object(shape), s) |

const { code } = await generateZodSourceFromOpenApi(spec, { useZodMini: true });

Example

Given examples/bookstore.openapi.json, running:

npx openapi-to-zod ./examples/bookstore.openapi.json ./examples/bookstore.generated.ts

Produces examples/bookstore.generated.ts:

// Auto-generated by @saunos/openapi-to-zod.
import { z } from 'zod';

const ErrorSchema = z.object({
  code: z.string(),
  message: z.string(),
});
const GenreSchema = z.enum(['fiction', 'non-fiction', 'science', 'history']);
const BookSchema = z.object({
  id: z.uuid(),
  title: z.string(),
  author: z.string(),
  get genre() {
    return GenreSchema;
  },
  published_at: z.iso.datetime(),
  rating: z.number().min(0).max(5).optional(),
});
const BookCreateSchema = z.object({
  title: z.string(),
  author: z.string(),
  get genre() {
    return GenreSchema;
  },
  published_at: z.union([z.iso.datetime(), z.null()]).optional(),
});
const BookPageSchema = z.object({
  get items() {
    return z.array(BookSchema);
  },
  total: z.int().min(0),
  page: z.int().min(1),
  size: z.int().min(1),
});

export const paths = {
  '/books': {
    get: {
      path: z.object({}),
      query: z.object({
        genre: z.enum(['fiction', 'non-fiction', 'science', 'history']),
        page: z.int().min(1),
        size: z.int().min(1).max(100),
      }),
      responses: {
        '200': BookPageSchema,
      },
    },
    post: {
      path: z.object({}),
      query: z.object({}),
      requestBody: {
        'application/json': BookCreateSchema,
      },
      responses: {
        '201': BookSchema,
      },
    },
  },
  '/books/{id}': {
    get: {
      path: z.object({
        id: z.uuid(),
      }),
      query: z.object({}),
      responses: {
        '200': BookSchema,
        '404': ErrorSchema,
      },
    },
  },
} as const;

export const components = {
  schemas: {
    Book: BookSchema,
    BookCreate: BookCreateSchema,
    BookPage: BookPageSchema,
    Error: ErrorSchema,
    Genre: GenreSchema,
  },
} as const;

With --mini:

npx openapi-to-zod ./examples/bookstore.openapi.json ./examples/bookstore.generated.ts --mini
// Auto-generated by @saunos/openapi-to-zod.
import * as z from 'zod/mini';

const ErrorSchema = z.object({
  code: z.string(),
  message: z.string(),
});
const GenreSchema = z.enum(['fiction', 'non-fiction', 'science', 'history']);
const BookSchema = z.object({
  id: z.uuid(),
  title: z.string(),
  author: z.string(),
  get genre() {
    return GenreSchema;
  },
  published_at: z.iso.datetime(),
  rating: z.optional(z.number().check(z.gte(0), z.lte(5))),
});
// ...
export const paths = {
  '/books': {
    get: {
      query: z.object({
        page: z.int().check(z.gte(1)),
        size: z.int().check(z.gte(1), z.lte(100)),
      }),
      // ...
    },
  },
} as const;

Generated exports

OpenAPI mode (generateZodSourceFromOpenApi)

Exports paths and components:

export const paths = {
  '/resource/{id}': {
    get: {
      path: z.object({ ... }),      // path parameters
      query: z.object({ ... }),     // query parameters
      requestBody: {                // optional — only present when defined
        'application/json': ...,
      },
      responses: {
        '200': ...,
      },
    },
  },
} as const;

export const components = {
  schemas: {
    MyModel: MyModelSchema,
  },
} as const;

JSON Schema mode (generateZodSourceFromJsonSchema)

Exports schema (the root) and defs (named $defs):

export const schema = z.object({ ... });
export const defs = {
  MyDef: MyDefSchema,
} as const;

Overrides

Replace any auto-generated expression at a JSON Pointer with your own:

const { code } = await generateZodSourceFromOpenApi(spec, {
  overrides: {
    '#/components/schemas/Date': 'z.coerce.date()',
    '#/components/schemas/User/properties/email': 'z.email().transform(v => v.toLowerCase())',
    // Replace an entire group with a single expression
    '#/paths/~1pets/get/queryParams': 'petsQuerySchema',
  },
});

Or via CLI:

npx openapi-to-zod api.json out.ts \
  --override "#/components/schemas/Date=z.coerce.date()" \
  --override "#/paths/~1pets/get/queryParams=petsQuerySchema"

License

MIT