UNPKG

zod-openapi

Version:

Convert Zod Schemas to OpenAPI v3.x documentation

1,018 lines (836 loc) 27 kB
<p align="center"> <img src="zod-openapi.png" width="200px" align="center" alt="zod-openapi logo" /> <h1 align="center">zod-openapi</h1> </p> <p align="center"> A TypeScript library which uses <a href="https://github.com/colinhacks/zod">Zod</a> schemas to generate OpenAPI v3.1x documentation. </p> <div align="center"> <a href="https://www.npmjs.com/package/zod-openapi"><img src="https://img.shields.io/npm/v/zod-openapi"/></a> <a href="https://www.npmjs.com/package/zod-openapi"><img src="https://img.shields.io/npm/dm/zod-openapi"/></a> <a href="https://nodejs.org/en/"><img src="https://img.shields.io/node/v/zod-openapi"/></a> <a href="https://github.com/samchungy/zod-openapi/actions/workflows/test.yml"><img src="https://github.com/samchungy/zod-openapi/actions/workflows/test.yml/badge.svg"/></a> <a href="https://github.com/samchungy/zod-openapi/actions/workflows/release.yml"><img src="https://github.com/samchungy/zod-openapi/actions/workflows/release.yml/badge.svg"/></a> <a href="https://github.com/seek-oss/skuba"><img src="https://img.shields.io/badge/🤿%20skuba-powered-009DC4"/></a> </div> <br> ## Installation Install via `npm`, `yarn`, or `pnpm`: ```bash npm install zod zod-openapi # or yarn add zod zod-openapi # or pnpm install zod zod-openapi ``` ## Usage ### `.meta()` Use Zod's native `.meta()` method to add OpenAPI metadata to your schemas. This library leverages Zod's built-in metadata functionality - no monkey patching or additional setup is required. Simply call `.meta()` on any Zod schema and it accepts an object with the following options: > **Note:** To get full TypeScript support for the OpenAPI-specific properties in `.meta()`, you need to import `zod-openapi` somewhere in your project. This import provides TypeScript type definitions that extend Zod's `.meta()` interface at compile-time (no runtime changes), enabling your IDE and TypeScript compiler to recognize the additional properties (like `id`, `param`, `header`, etc.). In most cases this will be done where you call `createDocument` or other zod-openapi functions. | Option | Description | | ---------- | ---------------------------------------------------------------------------------------------------------------- | | `id` | Registers a schema as a reusable OpenAPI component. | | `header` | Adds metadata for [response headers](#response-headers). | | `param` | Adds metadata for [request parameters](#parameters). | | `override` | Allows you to override the rendered OpenAPI schema. This takes either an object or a function. | | `outputId` | Allows you to set a different ID for the output schema. This is useful when the input and output schemas differ. | | `unusedIO` | Allows you to set the `io` for an unused schema added to the components section. Defaults to `output`. | You can also set standard OpenAPI properties directly in Zod's native `.meta()` method, such as: ```typescript z.string().meta({ description: 'A text field', example: 'Example value', }); ``` You can set additional metadata to the rendered schema in a few different ways. Zod's native `.meta()` method allows you to directly set OpenAPI properties to the schema. However, if you wanted to override any field that Zod generates, this may not work as expected. In this case, you can use the `override` option to customize the rendered OpenAPI schema. eg. ```typescript z.string().datetime().meta({ description: 'A date field', format: 'MY-FORMAT', 'x-custom-field': 'custom value', }); ``` Would render the following OpenAPI schema. Note that format is not overridden with our custom format value. ```json { "type": "string", "format": "date-time", "description": "A date field", "x-custom-field": "custom value" } ``` In order to override fields which are generated by Zod or this library, you can use the `override` option in Zod's `.meta()` method. This allows you to customize the rendered OpenAPI schema after we have both processed it. ##### override object This does a naive merge of the override object with the rendered OpenAPI schema. This is useful for simple overrides where you want to add or modify properties without complex logic. ```typescript z.string.datetime().meta({ description: 'A date field', override: { format: 'MY-FORMAT', }, }); ``` ##### override function The `override` function allows you to deeply customize the rendered OpenAPI schema. Eg. if you wanted to render a Zod union as a `oneOf` instead of `anyOf` for a single schema, you can do so by using the `override` function. View the documentation for `override` in the [CreateDocumentOptions](#createdocumentoptions) section for more information. ```typescript z.union([z.string(), z.number()]).meta({ description: 'A union of string and number', override: ({ jsonSchema }) => { jsonSchema.anyOf = jsonSchema.oneOf; delete jsonSchema.oneOf; }, }); ``` ### `createDocument` Generates an OpenAPI documentation object. ```typescript import * as z from 'zod/v4'; // or import * as z from 'zod'; if using Zod 4.0.0+ import { createDocument } from 'zod-openapi'; const jobId = z.string().meta({ description: 'A unique identifier for a job', example: '12345', id: 'jobId', }); const title = z.string().meta({ description: 'Job title', example: 'My job', }); const document = createDocument({ openapi: '3.1.0', info: { title: 'My API', version: '1.0.0', }, paths: { '/jobs/{jobId}': { put: { requestParams: { path: z.object({ jobId }) }, requestBody: { content: { 'application/json': { schema: z.object({ title }) }, }, }, responses: { '200': { description: '200 OK', content: { 'application/json': { schema: z.object({ jobId, title }) }, }, }, }, }, }, }, }); ``` <details> <summary>Creates the following object:</summary> ```json { "openapi": "3.1.0", "info": { "title": "My API", "version": "1.0.0" }, "paths": { "/jobs/{jobId}": { "put": { "parameters": [ { "in": "path", "name": "jobId", "description": "A unique identifier for a job", "schema": { "$ref": "#/components/schemas/jobId" } } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "Job title", "example": "My job" } }, "required": ["title"] } } } }, "responses": { "200": { "description": "200 OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "jobId": { "$ref": "#/components/schemas/jobId" }, "title": { "type": "string", "description": "Job title", "example": "My job" } }, "required": ["jobId", "title"] } } } } } } } }, "components": { "schemas": { "jobId": { "type": "string", "description": "A unique identifier for a job", "example": "12345" } } } } ``` </details> `createDocument` takes an optional options argument which can be used to modify how the document is created ```typescript createDocument(doc, { override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; } }, allowEmptySchema: { custom: true, }, }); ``` #### CreateDocumentOptions | Option | Type | Description | | ------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `override` | `Function` | Override rendered schema with a function`` | | `outputIdSuffix` | `string` | Suffix for output schema IDs when the schema is used in both a request and response. Defaults to ``'Output'` | | `allowEmptySchema` | `Object` | Control whether empty schemas are allowed for specific Zod schema types | | `cycles` | `'ref' \| 'throw'` | How to handle cycles in schemas.<br>- `'ref'` — Break cycles using $defs<br>- `'throw'` — Error on cycles. Defaults to `'ref'` | | `reused` | `'ref' \| 'inline'` | How to handle reused schemas.<br>- `'ref'` — Reused schemas as references<br>- `'inline'` — Inline reused schemas. Defaults to `'inline'` | | | ##### `override` The `override` function allows you to customize the rendered OpenAPI schema. It receives an object with the following properties: | Property | Type | Description | | ------------ | --------------------- | ----------------------------------------------------------------------------------------------------------------- | | `jsonSchema` | `Object` | The OpenAPI schema object being generated. You can modify this object to change the rendered schema. | | `zodSchema` | `ZodType` | The original Zod schema being converted to OpenAPI. You can use this to access Zod-specific properties. | | `io` | `'input' \| 'output'` | The context in which the schema is being rendered. `'input'` for request bodies/params, `'output'` for responses. | This allows you to transform the schema based on your own rules or requirements. For example, if you 1. Wanted to change how dates are rendered in the output context because a typical JSON serializer will transform them to a string 2. Change all union outputs to be oneOf instead of anyOf ```typescript createDocument(doc, { override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; return; } if (def.type === 'union') { jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; return; } }, }); ``` ##### `outputIdSuffix` The `outputIdSuffix` option allows you to set a suffix for output schema IDs when the schema is used in both a request and response context. This is useful for distinguishing between input and output schemas. ##### `allowEmptySchema` The `allowEmptySchema` option allows you to control whether or not this library will throw when it encounters an empty schema. By default this library will not throw if it encounters an `z.any()` or `z.unknown()` schema. This allows you to customize how this library handles [unrepresentable](https://zod.dev/json-schema?id=unrepresentable) Zod schemas. eg. If you wanted to allow `z.custom()` to be rendered as an empty schema, you can set the `allowEmptySchema` option as follows: ```typescript createDocument(doc, { allowEmptySchema: { custom: true, // Allow empty schemas for `z.custom()` in all contexts set: { output: true }, // Allow empty schemas for `z.set()` only in an output context }, }); ``` ##### `cycles` and `reused` These options are exposed directly from the Zod. Read the [documentation](https://zod.dev/json-schema?id=unrepresentable#cycles) for more information on how to use these options. ##### ### `createSchema` Creates an OpenAPI Schema Object along with any registered components. OpenAPI 3.1.0 Schema Objects are fully compatible with JSON Schema. ```typescript import * as z from 'zod/v4'; import { createSchema } from 'zod-openapi'; const jobId = z.string().meta({ description: 'A unique identifier for a job', example: '12345', id: 'jobId', }); const title = z.string().meta({ description: 'Job title', example: 'My job', }); const job = z.object({ jobId, title, }); const { schema, components } = createSchema(job); ``` <details> <summary>Creates the following object:</summary> ```json { "schema": { "type": "object", "properties": { "jobId": { "$ref": "#/components/schemas/jobId" }, "title": { "type": "string", "description": "Job title", "example": "My job" } }, "required": ["jobId", "title"] }, "components": { "jobId": { "type": "string", "description": "A unique identifier for a job", "example": "12345" } } } ``` </details> #### CreateSchemaOptions `createSchema` takes an optional `CreateSchemaOptions` parameter which includes all options from [CreateDocumentOptions](#createdocumentoptions) plus the following: ```typescript const { schema, components } = createSchema(job, { // Input/Output context - controls how schemas are generated io: 'input', // 'input' for request bodies/params, 'output' for responses // Component handling schemaComponents: { jobId: z.string() }, // Pre-defined components to use schemaComponentRefPath: '#/definitions/', // Custom path prefix for component references opts: {}, // Create Document Options, }); ``` ### Request Parameters Query, Path, Header & Cookie parameters can be created using the `requestParams` key under the `method` key as follows: ```typescript createDocument({ paths: { '/jobs/{a}': { put: { requestParams: { path: z.object({ a: z.string() }), query: z.object({ b: z.string() }), cookie: z.object({ cookie: z.string() }), header: z.object({ 'custom-header': z.string() }), }, }, }, }, }); ``` If you would like to declare parameters in a more traditional way you may also declare them using the [parameters](https://swagger.io/docs/specification/describing-parameters/) key. The definitions will then all be combined. ```ts createDocument({ paths: { '/jobs/{a}': { put: { parameters: [ z.string().meta({ param: { name: 'job-header', in: 'header', }, }), ], }, }, }, }); ``` ### Request Body Where you would normally declare the [media type](https://swagger.io/docs/specification/media-types/), set the `schema` as your Zod Schema as follows. ```typescript createDocument({ paths: { '/jobs': { get: { requestBody: { content: { 'application/json': { schema: z.object({ a: z.string() }) }, }, }, }, }, }, }); ``` If you wish to use OpenAPI syntax for your schemas, simply add an OpenAPI schema to the `schema` field instead. ### Responses Similarly to the [Request Body](#request-body), simply set the `schema` as your Zod Schema as follows. You can set the response headers using the `headers` key. ```typescript createDocument({ paths: { '/jobs': { get: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }) }, }, headers: z.object({ 'header-key': z.string(), }), }, }, }, }, }, }); ``` ### Callbacks ```typescript createDocument({ paths: { '/jobs': { get: { callbacks: { onData: { '{$request.query.callbackUrl}/data': { post: { requestBody: { content: { 'application/json': { schema: z.object({ a: z.string() }) }, }, }, responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }, }, }, }, }, }, }); ``` ### Creating Components OpenAPI allows you to define reusable [components](https://swagger.io/docs/specification/components/) and this library allows you to replicate that in two separate ways. 1. Auto registering schema 2. Manually registering schema #### Schema If we take the example in `createDocument` and instead create `title` as follows ##### Auto Registering Schema ```typescript const title = z.string().meta({ description: 'Job title', example: 'My job', id: 'jobTitle', // <- new field }); ``` Wherever `title` is used in schemas across the document, it will instead be created as a reference. ```json { "$ref": "#/components/schemas/jobTitle" } ``` `title` will then be outputted as a schema within the components section of the documentation. ```json { "components": { "schemas": { "jobTitle": { "type": "string", "description": "Job title", "example": "My job" } } } } ``` This is a great way to create less repetitive Open API documentation. There are some Open API features like [discriminator mapping](https://swagger.io/docs/specification/data-models/inheritance-and-polymorphism/) which require all schemas in the union to contain a ref. ##### Manually Registering Schema Another way to register schema instead of adding a `ref` is to add it to the components directly. This will still work in the same way as `ref`. So whenever we run into that Zod type we will replace it with a reference. eg. ```typescript const title = z.string().meta({ description: 'Job title', example: 'My job', }); createDocument({ components: { schemas: { jobTitle: title, // this will register this Zod Schema as jobTitle unless `id` in `.meta()` is specified on the type }, }, }); ``` #### Parameters Query, Path, Header & Cookie parameters can be similarly registered: ```typescript // Easy auto registration const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { id: 'jobRef' }, }); createDocument({ paths: { '/jobs/{jobId}': { put: { requestParams: { header: z.object({ jobId, }), }, }, }, }, }); // or more verbose auto registration const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId', id: 'jobRef' }, }); createDocument({ paths: { '/jobs/{jobId}': { put: { parameters: [jobId], }, }, }, }); // or manual registration const otherJobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId' }, }); createDocument({ components: { parameters: { jobRef: jobId, }, }, }); ``` #### Response Headers Response headers can be similarly registered: ```typescript const header = z.string().meta({ description: 'Job ID', example: '1234', header: { id: 'some-header' }, }); // or const jobIdHeader = z.string().meta({ description: 'Job ID', example: '1234', }); createDocument({ components: { headers: { someHeaderRef: jobIdHeader, }, }, }); ``` #### Responses Entire Responses can also be registered ```typescript const response: ZodOpenApiResponseObject = { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, id: 'some-response', }; //or const response: ZodOpenApiResponseObject = { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }; createDocument({ components: { responses: { 'some-response': response, }, }, }); ``` #### Callbacks Callbacks can also be registered ```typescript const callback: ZodOpenApiCallbackObject = { id: 'some-callback' post: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }; //or const callback: ZodOpenApiCallbackObject = { post: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }; createDocument({ components: { callbacks: { 'some-callback': callback, }, }, }); ``` #### Path Items Path Items can also be registered ```typescript const pathItem: ZodOpenApiPathItemObject = { id: 'some-path-item', get: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }; // or createDocument({ components: { pathItems: { 'some-path-item': pathItem, }, }, }); ``` #### Security Schemes Security Schemes can be registered for authentication methods: ```typescript createDocument({ components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', description: 'JWT Authentication', }, }, }, }); ``` #### Links Links can be registered to describe relationships between operations: ```typescript const link: ZodOpenApiLinkObject = { id: 'getUserById', operationId: 'getUser', parameters: { userId: '$request.path.id', }, description: 'Link to get user by id', }; // or createDocument({ components: { links: { getUserById: { operationId: 'getUser', parameters: { userId: '$request.path.id', }, description: 'Link to get user by id', }, }, }, }); ``` #### Examples Examples can be registered to provide sample values for schemas: ```typescript const example: ZodOpenApiExampleObject = { id: 'userExample', summary: 'A sample user', value: { id: '123', name: 'Jane Doe', email: 'jane@example.com', }, }; // or createDocument({ components: { examples: { userExample: { summary: 'A sample user', value: { id: '123', name: 'Jane Doe', email: 'jane@example.com', }, }, }, }, }); ``` ### Zod Types Zod types are composed of two different parts: the input and the output. This library decides which type to create based on if it is used in a request or response context. Input: - Request Parameters (query, path, header, cookie) - Request Body Output: - Response Body - Response Headers In general, you want to avoid using a registered input schema in an output context and vice versa. This is because the rendered input and output schemas of a simple Zod schema will differ, even with a simple Zod schema like `z.object()`. ```typescript const schema = z.object({ name: z.string(), }); ``` Input schemas (request bodies, parameters): ```json { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] } ``` Output schemas (responses): ```json { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"], "additionalProperties": false } ``` When the same schema is referenced in both input and output contexts, the library generates two separate component schemas. This happens automatically when a schema with an ID is used in both contexts. You can customize the output schema name by providing an `outputId`: ```ts const schema = z .object({ name: z.string(), }) .meta({ id: 'MyObject', outputId: 'MyObjectResponse', // Customize the output schema name }); ``` You can also set a global suffix for output schemas or use `z.looseObject()` and `z.strictObject()` to have explicit control over the schema behavior. > **⚠️ Note:** If your registered schema contains dynamically created lazy components, they won't be reused between input and output schemas. ## Supported OpenAPI Versions Currently the following versions of OpenAPI are supported - `3.1.0` (minimum version) - `3.1.1` Setting the `openapi` field will change how the some of the components are rendered. ```ts createDocument({ openapi: '3.1.0', }); ``` As an example `z.string().nullable()` will be rendered differently `3.0.0` ```json { "type": "string", "nullable": true } ``` `3.1.0` ```json { "type": ["string", "null"] } ``` ## Examples See the library in use in the [examples](./examples/) folder. - Simple - [setup](./examples/simple/createSchema.ts) | [openapi.yml](./examples/simple/openapi.yml) | [redoc documentation](https://samchungy.github.io/zod-openapi/examples/simple/redoc-static.html) ## Ecosystem - [fastify-zod-openapi](https://github.com/samchungy/fastify-zod-openapi) - Fastify plugin for zod-openapi. This includes type provider, Zod schema validation, Zod schema serialization and Swagger UI support. - [eslint-plugin-zod-openapi](https://github.com/samchungy/eslint-plugin-zod-openapi) - Eslint rules for zod-openapi. This includes features which can autogenerate Typescript comments for your Zod types based on your `description`, `example` and `deprecated` fields. ## Version Information For information about changes and migration from v4 to v5, see the [v5 migration guide](./docs/v5.md). ## Development ### Prerequisites - Node.js LTS - pnpm ```shell pnpm pnpm build ``` ### Test ```shell pnpm test ``` ### Lint ```shell # Fix issues pnpm format # Check for issues pnpm lint ```