zod-openapi v3.3.0
Install
Install via npm, yarn or pnpm:
npm install zod zod-openapi
## or
yarn add zod zod-openapi
## or
pnpm install zod zod-openapiUsage
Extend Zod
This mutates Zod to add an extra .openapi() method. Call this at the top of your entry point(s). You can achieve this in two different ways, depending on your preference.
Subpath Import
import 'zod-openapi/extend';
import { z } from 'zod';
z.string().openapi({ description: 'hello world!', example: 'hello world' });Manual Extension
This is useful if you have a specific instance of Zod or a Zod instance from another library that you would like to target.
import { z } from 'zod';
import { extendZodWithOpenApi } from 'zod-openapi';
extendZodWithOpenApi(z);
z.string().openapi({ description: 'hello world!', example: 'hello world' });.openapi()
Use the .openapi() method to add metadata to a specific Zod type. The .openapi() method takes an object with the following options:
| Option | Description |
|---|---|
| OpenAPI Options | This will take any option you would put on a SchemaObject. |
effectType | Use to override the creation type for a Zod Effect |
header | Use to provide metadata for response headers |
param | Use to provide metadata for request parameters |
ref | Use this to auto register a schema as a re-usable component |
refType | Use this to set the creation type for a component which is not referenced in the document. |
type | Use this to override the generated type. If this is provided no metadata will be generated. |
unionOneOf | Set to true to force a single ZodUnion to output oneOf instead of allOf. See CreateDocumentOptions for a global option |
createDocument
Creates an OpenAPI documentation object
import 'zod-openapi/extend';
import { z } from 'zod';
import { createDocument } from 'zod-openapi';
const jobId = z.string().openapi({
description: 'A unique identifier for a job',
example: '12345',
ref: 'jobId',
});
const title = z.string().openapi({
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 }) },
},
},
},
},
},
},
});CreateDocumentOptions
createDocument takes an optional CreateDocumentOptions argument which can be used to modify how the document is created.
const document = createDocument(details, {
defaultDateSchema: { type: 'string', format: 'date-time' }, // defaults to { type: 'string' }
unionOneOf: true, // defaults to false. Forces all ZodUnions to output oneOf instead of allOf. An `.openapi()` `unionOneOf` value takes precedence over this one.
});createSchema
Creates an OpenAPI Schema Object along with any registered components. OpenAPI 3.1.0 Schema Objects are fully compatible with JSON Schema.
import 'zod-openapi/extend';
import { z } from 'zod';
import { createSchema } from 'zod-openapi';
const jobId = z.string().openapi({
description: 'A unique identifier for a job',
example: '12345',
ref: 'jobId',
});
const title = z.string().openapi({
description: 'Job title',
example: 'My job',
});
const job = z.object({
jobId,
title,
});
const { schema, components } = createSchema(job);CreateSchemaOptions
createSchema takes an optional CreateSchemaOptions parameter which can also take the same options as CreateDocumentOptions along with the following options:
const { schema, components } = createSchema(job, {
schemaType: 'input'; // This controls whether this should be rendered as a request (`input`) or response (`output`). Defaults to `output`
openapi: '3.0.0'; // OpenAPI version to use, defaults to `'3.1.0'`
components: { jobId: z.string() } // Additional components to use and create while rendering the schema
componentRefPath: '#/definitions/' // Defaults to #/components/schemas/
})Request Parameters
Query, Path, Header & Cookie parameters can be created using the requestParams key under the method key as follows:
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 key. The definitions will then all be combined.
createDocument({
paths: {
'/jobs/{a}': {
put: {
parameters: [
z.string().openapi({
param: {
name: 'job-header',
in: 'header',
},
}),
],
},
},
},
});Request Body
Where you would normally declare the media type, set the schema as your Zod Schema as follows.
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, simply set the schema as your Zod Schema as follows. You can set the response headers using the headers key.
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
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 and this library allows you to replicate that in two separate ways.
- Auto registering schema
- Manually registering schema
Schema
If we take the example in createDocument and instead create title as follows
Auto Registering Schema
const title = z.string().openapi({
description: 'Job title',
example: 'My job',
ref: 'jobTitle', // <- new field
});Wherever title is used in schemas across the document, it will instead be created as a reference.
{ "$ref": "#/components/schemas/jobTitle" }title will then be outputted as a schema within the components section of the documentation.
{
"components": {
"schemas": {
"jobTitle": {
"type": "string",
"description": "Job title",
"example": "My job"
}
}
}
}This can be an extremely powerful way to create less repetitive Open API documentation. There are some Open API features like discriminator mapping 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.
createDocument({
components: {
schemas: {
jobTitle: title, // this will register this Zod Schema as jobTitle unless `ref` in `.openapi()` is specified on the type
},
},
});Zod Effects
.transform(), .catch(), .default() and .pipe() are complicated because they technically comprise of two types (input & output). This means that we need to understand which type you are creating. In particular with transform it is very difficult to infer the output type. This library will automatically select which type to use by checking how the schema is used based on the following rules:
Input: Request Bodies, Request Parameters, Headers
Output: Responses, Response Headers
If a registered schema with a transform or pipeline is used in both a request and response schema you will receive an error because the created schema for each will be different. To override the creation type for a specific ZodEffect, add an .openapi() field on it and set the effectType field to input, output or same. This will force this library to always generate the input/output type even if we are creating a response (output) or request (input) type. You typically want to set this when you know the type has not changed in the transform. same is the recommended choice as it will generate a TypeScript compiler error if the input and output types in the transform drift.
.preprocess() will always return the output type even if we are creating an input schema. If a different input type is required you can achieve this with a .transform() combined with a .pipe() or simply declare a manual type in .openapi().
If you are adding a ZodSchema directly to the components section which is not referenced anywhere in the document, additional context may be required to create either an input or output schema. You can do this by setting the refType field to input or output in .openapi(). This defaults to output by default.
Parameters
Query, Path, Header & Cookie parameters can be similarly registered:
// Easy auto registration
const jobId = z.string().openapi({
description: 'Job ID',
example: '1234',
param: { ref: 'jobRef' },
});
createDocument({
paths: {
'/jobs/{jobId}': {
put: {
requestParams: {
header: z.object({
jobId,
}),
},
},
},
},
});
// or more verbose auto registration
const jobId = z.string().openapi({
description: 'Job ID',
example: '1234',
param: { in: 'header', name: 'jobId', ref: 'jobRef' },
});
createDocument({
paths: {
'/jobs/{jobId}': {
put: {
parameters: [jobId],
},
},
},
});
// or manual registeration
const otherJobId = z.string().openapi({
description: 'Job ID',
example: '1234',
param: { in: 'header', name: 'jobId' },
});
createDocument({
components: {
parameters: {
jobRef: jobId,
},
},
});Response Headers
Response headers can be similarly registered:
const header = z.string().openapi({
description: 'Job ID',
example: '1234',
header: { ref: 'some-header' },
});
// or
const jobIdHeader = z.string().openapi({
description: 'Job ID',
example: '1234',
});
createDocument({
components: {
headers: {
someHeaderRef: jobIdHeader,
},
},
});Responses
Entire Responses can also be registered
const response: ZodOpenApiResponseObject = {
description: '200 OK',
content: {
'application/json': {
schema: z.object({ a: z.string() }),
},
},
ref: '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
const callback: ZodOpenApiCallbackObject = {
ref: '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,
},
},
});Supported OpenAPI Versions
Currently the following versions of OpenAPI are supported
3.0.03.0.13.0.23.0.33.1.0
Setting the openapi field will change how the some of the components are rendered.
createDocument({
openapi: '3.1.0',
});For example in z.string().nullable() will be rendered differently
3.0.0
{
"type": "string",
"nullable": true
}3.1.0
{
"type": ["string", "null"]
}Supported Zod Schema
- ZodAny
- ZodArray
minItems/maxItemsmapping for.length(),.min(),.max()
- ZodBoolean
- ZodBranded
- ZodCatch
- Treated as ZodDefault
- ZodCustom
- ZodDate
typeis mapped asstringby default
- ZodDefault
- ZodDiscriminatedUnion
discriminatormapping when all schemas in the union are registered. The discriminator must be aZodLiteral,ZodEnumorZodNativeEnumwith string values. Only values wrapped inZodBranded,ZodReadOnlyandZodCatchare supported.
- ZodEffects
transformsupport for request schemas. See Zod Effects for how to enable response schema supportpre-processsupport. We assume that the input type is the same as the output type. Otherwise pipe and transform can be used instead.refinefull support
- ZodEnum
- ZodIntersection
- ZodLazy
- The recursive schema within the ZodLazy or the ZodLazy must be registered as a component. See Creating Components for more information.
- ZodLiteral
- ZodNativeEnum
- supporting
string,numberand combined enums.
- supporting
- ZodNever
- ZodNull
- ZodNullable
- ZodNumber
integertypemapping for.int()exclusiveMin/min/exclusiveMax/maxmapping for.min(),.max(),lt(),gt()
- ZodObject
additionalPropertiesmapping for.catchall(),.strict()allOfmapping for.extend()when the base object is registered and does not havecatchall(),strict()and extension does not override a field.
- ZodOptional
- ZodPipeline
- See Zod Effects for more information.
- ZodReadonly
- ZodRecord
- ZodSet
- Treated as an array with
uniqueItems(you may need to add a pre-process to convert it to a set)
- Treated as an array with
- ZodString
formatmapping for.url(),.uuid(),.email(),.datetime(),.date(),.time(),.duration()minLength/maxLengthmapping for.length(),.min(),.max()patternmapping for.regex(),.startsWith(),.endsWith(),.includes()contentEncodingmapping for.base64()for OpenAPI 3.1.0+
- ZodTuple
itemsmapping for.rest()prefixItemsmapping for OpenAPI 3.1.0+
- ZodUndefined
- ZodUnion
- By default it outputs an
allOfschema. UseunionOneOfto change this to outputoneOfinstead.
- By default it outputs an
- ZodUnknown
If this library cannot determine a type for a Zod Schema, it will throw an error. To avoid this, declare a manual type in the .openapi() section of that schema.
eg.
z.custom().openapi({ type: 'string' });Examples
See the library in use in the examples folder.
- Simple - setup | openapi.yml | redoc documentation
Ecosystem
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 - Eslint rules for zod-openapi. This includes features which can autogenerate Typescript comments for your Zod types based on your
description,exampleanddeprecatedfields.
Comparisons
@asteasolutions/zod-to-openapi
Development
Prerequisites
- Node.js LTS
- pnpm
pnpm
pnpm buildTest
pnpm testLint
# Fix issues
pnpm format
# Check for issues
pnpm lintRelease
To release a new version
- Create a new GitHub Release
- Select
🏷️ Choose a tag, enter a version number. eg.v1.2.0and click+ Create new tag: vX.X.X on publish. - Click the
Generate release notesbutton and adjust the description. - Tick the
Set as the latest releasebox and clickPublish release. This will trigger theReleaseworkflow. - Check the
Pull Requeststab for a PR labelledRelease vX.X.X. - Click
Merge Pull Requeston that Pull Request to update master with the new package version.
To release a new beta version
- Create a new GitHub Release
- Select
🏷️ Choose a tag, enter a version number with a-beta.Xsuffix eg.v1.2.0-beta.1and click+ Create new tag: vX.X.X-beta.X on publish. - Click the
Generate release notesbutton and adjust the description. - Tick the
Set as a pre-releasebox and clickPublish release. This will trigger thePrereleaseworkflow.
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago