MCPcopy Index your code
hub / github.com/asteasolutions/zod-to-openapi

github.com/asteasolutions/zod-to-openapi @v8.5.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v8.5.0 ↗ · + Follow
245 symbols 662 edges 86 files 15 documented · 6% 11 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Zod to OpenAPI

npm version npm downloads

[!IMPORTANT] For Zod v3 support, please use the v7.3.4 version. However keep in mind that we do not intend to actively support that version going forward Install with: npm install @asteasolutions/zod-to-openapi@7.3.4

A library that uses zod schemas to generate an Open API Swagger documentation.

  1. Purpose and quick example
  2. Usage
  3. Installation
  4. The openapi method
  5. The Registry
  6. The Generator
  7. Defining schemas
  8. Defining routes & webhooks
  9. Defining custom components
  10. A full example
  11. Adding it as part of your build
  12. Using schemas vs a registry
  13. Generation options
  14. Zod schema types
  15. Supported types
  16. Unsupported types
  17. Technologies

We keep a changelog as part of the GitHub releases.

Purpose and quick example

We at Astea Solutions made this library because we use zod for validation in our APIs and are tired of the duplication to also support a separate OpenAPI definition that must be kept in sync. Using zod-to-openapi, we generate OpenAPI definitions directly from our zod schemas, thus having a single source of truth.

Simply put, it turns this:

const UserSchema = z
  .object({
    id: z.string().openapi({ example: '1212121' }),
    name: z.string().openapi({ example: 'John Doe' }),
    age: z.number().openapi({ example: 42 }),
  })
  .openapi('User');

registry.registerPath({
  method: 'get',
  path: '/users/{id}',
  summary: 'Get a single user',
  request: {
    params: z.object({ id: z.string() }),
  },

  responses: {
    200: {
      description: 'Object with user data.',
      content: {
        'application/json': {
          schema: UserSchema,
        },
      },
    },
  },
});

into this:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          example: '1212121'
        name:
          type: string
          example: John Doe
        age:
          type: number
          example: 42
      required:
        - id
        - name
        - age

/users/{id}:
  get:
    summary: Get a single user
    parameters:
      - in: path
        name: id
        schema:
          type: string
        required: true
    responses:
      '200':
        description: Object with user data
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/User'

and you can still use UserSchema and the request.params object to validate the input of your API.

Usage

Installation

npm install @asteasolutions/zod-to-openapi
# or
yarn add @asteasolutions/zod-to-openapi

The openapi method

To keep openapi definitions natural, we add an openapi method to all Zod objects. Its idea is to provide a convenient way to provide OpenApi specific data. It has three overloads:

  1. .openapi({ [key]: value }) - this way we can specify any OpenApi fields. For example z.number().openapi({ example: 3 }) would add example: 3 to the generated schema.
  2. .openapi("<schema-name>") - this way we specify that the underlying zod schema should be "registered" i.e added into components/schemas with the provided <schema-name>
  3. .openapi("<schema-name>", { [key]: value }) - this unites the two use cases above so that we can specify both a registration <schema-name> and additional metadata

For this to work, you need to call extendZodWithOpenApi once in your project.

This should be done only once in a common-entrypoint file of your project (for example an index.ts/app.ts). If you're using tree-shaking with Webpack, mark that file as having side-effects.

It can be bit tricky to achieve this in your codebase, because require is synchronous and import is a async.

Using zod's .meta

Starting from v8 (and zod v4) you can also use zod's .meta to provide metadata and we will read it accordingly.

With zod's new option for generating JSON schemas and maintaining registries we've added a pretty much seamless support for all metadata information coming from .meta calls as if that was metadata passed into .openapi.

So the following 2 schemas produce exactly the same results:

const schema = z
  .string()
  .openapi('Schema', { description: 'Name of the user', example: 'Test' });

const schema2 = z
  .string()
  .meta({ id: 'Schema2', description: 'Name of the user', example: 'Test' });

Note: This also means that you unless you are using some of our more complicated scenarios you could even generate a schema without using extendZodWithOpenApi in your codebase and only rely on .meta to provide additional metadata information and schema names (using the id property).

Scenarios that require using extendZodWithOpenApi and .openapi

  1. When extending registered schemas that are both registered and want the extended one to use anyOf i.e:
const schema = z.object({ name: z.string() }).openapi('Schema');

const schema2 = schema.extend({ age: z.number() }).openapi('Schema2'); // this one would have anyOf and a reference to the first one
  1. Defining parameter metadata. So for example when doing:
registry.registerPath({
  // ...
  request: {
    query: z.object({
      name: z.string().openapi({
        description: 'Schema level description',
        param: { description: 'Param level description' },
      }),
    }),
  },
});

the result would be:

  "parameters": [
      {
        "schema": {
          "type": "string",
          "description": "Schema level description" // comes directly from description
        },
        "required": true,
        "description": "Param level description", // comes from param.description
        "name": "name",
        "in": "query"
      }
  ],

The basic idea

import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

extendZodWithOpenApi(z);

// We can now use `.openapi()` to specify OpenAPI metadata
z.string().openapi({ description: 'Some string' });

Example 1: Calling the openapi-extension using tsx

//zod-extend.ts

import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

extendZodWithOpenApi(z);

// package.json

  "scripts": {
    "start": "tsx --import ./zod-extend.ts ./index.ts",

Example 2 - require-syntax

import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

extendZodWithOpenApi(z);

const { startServer } = require('./server/start');
startServer();

The Registry

The OpenAPIRegistry is a utility that can be used to collect definitions which would later be passed to a OpenApiGeneratorV3 or OpenApiGeneratorV31 instance.

import {
  OpenAPIRegistry,
  OpenApiGeneratorV3,
} from '@asteasolutions/zod-to-openapi';

const registry = new OpenAPIRegistry();

// Register definitions here

const generator = new OpenApiGeneratorV3(registry.definitions);

return generator.generateComponents();

The Generator

There are two generators that can be used - OpenApiGeneratorV3 and OpenApiGeneratorV31. They share the same interface but internally generate schemas that correctly follow the data format for the specific Open API version - 3.0.x or 3.1.x. The Open API version affects how some components are generated.

For example: changing the generator from OpenApiGeneratorV3 to OpenApiGeneratorV31 would result in following differences:

z.string().nullable().openapi({refId: 'name'});
# 3.1.0
# nullable is invalid in 3.1.0 but type arrays are invalid in previous versions
name:
  type:
    - 'string'
    - 'null'

# 3.0.0
name:
  type: 'string'
  nullable: true

Both generators take a single argument in their constructors - an array of definitions - i.e results from the registry or regular zod schemas.

The public methods of both generators are as follows:

generateComponents will generate only the /components section of an OpenAPI document (e.g. only schemas and parameters), not generating actual routes.

generateDocument will generate the whole OpenAPI document.

Defining schemas

An OpenApi schema should be registered by using the .openapi method and providing a name:

const UserSchema = z
  .object({
    id: z.string().openapi({ example: '1212121' }),
    name: z.string().openapi({ example: 'John Doe' }),
    age: z.number().openapi({ example: 42 }),
  })
  .openapi('User');

const generator = new OpenApiGeneratorV3([UserSchema]);

The same can be achieved by using the register method of an OpenAPIRegistry instance. For more check the "Using schemas vs a registry" section

const UserSchema = registry.register(
  'User',
  z.object({
    id: z.string().openapi({ example: '1212121' }),
    name: z.string().openapi({ example: 'John Doe' }),
    age: z.number().openapi({ example: 42 }),
  })
);

const generator = new OpenApiGeneratorV3(registry.definitions);

If run now, generator.generateComponents() will generate the following structure:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          example: '1212121'
        name:
          type: string
          example: John Doe
        age:
          type: number
          example: 42
      required:
        - id
        - name
        - age

The key for the schema in the output is the first argument passed to .openapi method (or the .register) - in this case: User.

Note that generateComponents does not return YAML but a JS object - you can then serialize that object into YAML or JSON depending on your use-case.

The resulting schema can then be referenced by using $ref: #/components/schemas/User in an existing OpenAPI JSON. This will be done automatically for Routes defined through the registry.

Note by default a Zod object will result in "additionalProperties": true as per the Open API spec unless using strict or catchall, this is in contrast to normal Zod object usage where zod.parse is used.

Defining routes & webhooks

Registering a path or webhook

An OpenAPI path is registered using the registerPath method of an OpenAPIRegistry instance. An OpenAPI webhook is registered using the registerWebhook method and takes the same parameters as registerPath.

registry.registerPath({
  method: 'get',
  path: '/users/{id}',
  description: 'Get user data by its id',
  summary: 'Get a single user',
  request: {
    params: z.object({
      id: z.string().openapi({ example: '1212121' }),
    }),
  },
  responses: {
    200: {
      description: 'Object with user data.',
      content: {
        'application/json': {
          schema: UserSchema,
        },
      },
    },
    204: {
      description: 'No content - successful operation',
    },
  },
});

The YAML equivalent of the schema above would be:

'/users/{id}':
  get:
    description: Get user data by its id
    summary: Get a single user
    parameters:
      - in: path
        name: id
        schema:
          type: string
          example: '1212121'
        required: true
    responses:
      '200':
        description: Object with user data.
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/User'
      '204':
        description: No content - successful operation

The library specific properties for registerPath are method, path, request and responses. Everything else gets directly appended to the path definition.

  • method - One of get, post, put, delete and patch;
  • path - a string - being the path of the endpoint;
  • request - an optional object with optional body, params, query and headers keys,
  • query, params - being instances of ZodObject
  • body - an object with a description and a content record where:
    • the key is a mediaType string like application/json
    • and the value is an object with a schema of any zod type
  • headers - instances of ZodObject or an array of any zod instances
  • responses - an object where the key is the status code or default and the value is an object with a description and a content record where:
  • the key is a mediaType string like application/json
  • and the value is an object with a schema of any zod type

Defining route parameters

If you don't want to inline all parameter definitions, you can define them separately with registerParameter and then reference them:

const UserIdParam = registry.registerParameter(
  'UserId',
  z.string().openapi({
    param: {
      name: 'id',
      in: 'path',
    },
    example: '1212121',
  })
);

registry.registerPath({
  ...
  request: {
    params: z.object({
      id: UserIdParam
    }),
  },
  responses: ...
});

The YAML equivalent would be:

```yaml components: parameters: UserId: in: path name: id schema: type: string example: '1212121' required: true

'/users/{id}': get: ...

Extension points exported contracts — how you extend this code

OpenApiVersionSpecifics (Interface)
(no doc) [4 implementers]
src/openapi-generator.ts
InternalUserOnlyZodOpenAPIInternalMetadata (Interface)
* * Since this commit https://github.com/colinhacks/zod/commit/6707ebb14c885b1c577ce64a240475e26e3ff182 * zod started
src/zod-extensions.ts
RouteBasedUnionSchemas (Interface)
* Test: The exact RouteBasedUnionSchemas pattern from nw-data-definitions * * This interface pattern was causing compi
spec/type-definitions/zod-extensions.test-d.ts
ZodMediaTypeObject (Interface)
(no doc)
src/openapi-registry.ts
ConflictErrorProps (Interface)
(no doc)
src/errors.ts
ParameterData (Interface)
(no doc)
src/openapi-generator.ts
OpenApiOptions (Interface)
(no doc)
src/zod-extensions.ts
ZodRequestBody (Interface)
(no doc)
src/openapi-registry.ts

Core symbols most depended-on inside this repo

openapi
called by 368
src/zod-extensions.ts
expectSchema
called by 211
spec/lib/helpers.ts
isZodType
called by 45
src/lib/zod-is-type.ts
generateDataForRoute
called by 32
spec/lib/helpers.ts
mapNullableType
called by 17
src/openapi-generator.ts
transform
called by 17
src/transformers/lazy.ts
isAnyZodType
called by 15
src/lib/zod-is-type.ts
transform
called by 14
src/transformers/index.ts

Shape

Method 116
Class 60
Function 50
Interface 16
Enum 3

Languages

TypeScript100%

Modules by API surface

src/openapi-generator.ts39 symbols
src/metadata.ts17 symbols
src/errors.ts16 symbols
src/openapi-registry.ts13 symbols
src/zod-extensions.ts11 symbols
spec/types/recursive-schemas.spec.ts11 symbols
src/v3.1/specifics.ts8 symbols
src/v3.0/specifics.ts8 symbols
src/lib/object-set.ts8 symbols
src/lib/lodash.ts8 symbols
src/v3.1/openapi-generator.ts7 symbols
src/transformers/union.ts6 symbols

For agents

$ claude mcp add zod-to-openapi \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page