Security News
npm Updates Search Experience with New Objective Sorting Options
npm has a revamped search experience with new, more transparent sorting options—Relevance, Downloads, Dependents, and Publish Date.
@asteasolutions/zod-to-openapi
Advanced tools
@asteasolutions/zod-to-openapi is an npm package that allows you to convert Zod schemas to OpenAPI (Swagger) definitions. This is particularly useful for generating API documentation from your Zod validation schemas, ensuring that your API documentation stays in sync with your validation logic.
Convert Zod Schema to OpenAPI Schema
This feature allows you to convert a Zod schema into an OpenAPI schema. The code sample demonstrates how to define a Zod schema for a user object and then convert it into an OpenAPI schema.
const { z } = require('zod');
const { openApi } = require('@asteasolutions/zod-to-openapi');
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
const openApiSchema = openApi({
title: 'User',
version: '1.0.0',
schema: userSchema
});
console.log(JSON.stringify(openApiSchema, null, 2));
Generate OpenAPI Documentation
This feature allows you to generate a complete OpenAPI document from Zod schemas. The code sample demonstrates how to define a Zod schema for a user object, convert it into an OpenAPI schema, and then generate an OpenAPI document that includes an endpoint for retrieving users.
const { z } = require('zod');
const { openApi, generateOpenApiDocument } = require('@asteasolutions/zod-to-openapi');
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
const openApiSchema = openApi({
title: 'User',
version: '1.0.0',
schema: userSchema
});
const openApiDocument = generateOpenApiDocument({
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0'
},
paths: {
'/users': {
get: {
summary: 'Get Users',
responses: {
'200': {
description: 'A list of users',
content: {
'application/json': {
schema: openApiSchema
}
}
}
}
}
}
}
});
console.log(JSON.stringify(openApiDocument, null, 2));
zod-to-json-schema is a package that converts Zod schemas to JSON Schema. While it does not directly generate OpenAPI documentation, JSON Schema is a core part of OpenAPI, so you can use the generated JSON Schema as part of your OpenAPI definitions. Compared to @asteasolutions/zod-to-openapi, it requires additional steps to integrate with OpenAPI.
swagger-jsdoc is a package that generates OpenAPI (Swagger) documentation from JSDoc comments in your code. Unlike @asteasolutions/zod-to-openapi, which generates OpenAPI schemas from Zod validation schemas, swagger-jsdoc relies on JSDoc comments to generate the documentation. This can be more flexible but requires you to maintain JSDoc comments separately from your validation logic.
openapi-typescript is a package that generates TypeScript types from OpenAPI schemas. While it operates in the opposite direction compared to @asteasolutions/zod-to-openapi (which generates OpenAPI schemas from Zod schemas), it can be used in conjunction with @asteasolutions/zod-to-openapi to ensure type safety across your API documentation and TypeScript codebase.
A library that uses zod schemas to generate an Open API Swagger documentation.
We keep a changelog as part of the GitHub releases.
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.
npm install @asteasolutions/zod-to-openapi
# or
yarn add @asteasolutions/zod-to-openapi
openapi
methodTo 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:
.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..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>
.openapi("<schema-name>", { [key]: value })
- this unites the two use cases above so that we can specify both a registration <schema-name>
and additional metadataFor this to work, you need to call extendZodWithOpenApi
once in your project.
Note: 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.
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' });
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();
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.
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.
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:
mediaType
string like application/json
schema
of any zod
typeheaders
- instances of ZodObject
or an array of any zod
instancesresponses
- 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:
mediaType
string like application/json
schema
of any zod
typeIf 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:
components:
parameters:
UserId:
in: path
name: id
schema:
type: string
example: '1212121'
required: true
'/users/{id}':
get:
...
parameters:
- $ref: '#/components/parameters/UserId'
responses: ...
Note: In order to define properties that apply to the parameter itself, use the param
property of .openapi
. Any properties provided outside of param
would be applied to the schema for this parameter.
A full OpenAPI document can be generated using the generateDocument
method of an OpenApiGeneratorV3
or OpenApiGeneratorV31
instance. It takes one argument - the document config. It may look something like this:
return generator.generateDocument({
openapi: '3.0.0',
info: {
version: '1.0.0',
title: 'My API',
description: 'This is the API',
},
servers: [{ url: 'v1' }],
});
You can define components that are not OpenAPI schemas, including security schemes, response headers and others. See this test file for examples.
A full example code can be found here. And the YAML representation of its result - here
Schemas are automatically being registered when referenced. That means that if you have a schema like:
const schema = z.object({ key: z.string().openapi('Test') }).openapi('Object');
you'd have the following resulting structure:
components:
schemas:
Test:
type: 'string',
Object:
type: 'object',
properties:
key:
$ref: '#/components/schemas/Test'
required: ['key']
This does not require any usages of an OpenAPIRegistry
instance.
However the same output can be achieved with the following code:
const registry = new OpenAPIRegistry();
const schema = registry.register(
'Object',
z.object({ key: z.string().openapi('Test') })
);
The main benefit of the .registry
method is that you can use the registry as a "collection" where you would put all such schemas.
With .openapi
:
// file1.ts
export const Schema1 = ...
// file2.ts
export const Schema2 = ...
new OpenApiGeneratorV3([Schema1, Schema2])
Adding a NewSchema
into file3.ts
would require you to pass that schema manually into the array of the generator constructor.
Note: If a NewSchema
is referenced by any other schemas or a route/webhook definition it would still appear in the resulting document.
With registry.register
:
// registry.ts
export const registry = new OpenAPIRegistry()
// file1.ts
export const Schema1 = registry.register(...)
// file2.ts
export const Schema2 = registry.register(...)
new OpenApiGeneratorV3(registry.definitions)
Adding a NewSchema
into file3.ts
and using registry.register
would NOT require you to do any changes to the generator constructor.
Using an OpenAPIRegistry
instance is mostly useful if you would want your resulting document to contain unreferenced schemas.
That can sometimes be useful - for example when you are slowly integrating an already existing documentation with @asteasolutions/zod-to-openapi
and you are migrating small pieces at a time. Those pieces can then be referenced directly from an existing documentation.
In a file inside your project you can have a file like so:
export const registry = new OpenAPIRegistry();
export function generateOpenAPI() {
const config = {...}; // your config comes here
return new OpenApiGeneratorV3(schemas.definitions).generateDocument(config);
}
You then use the exported registry
object to register all schemas, parameters and routes where appropriate.
Then you can create a script that executes the exported generateOpenAPI
function. This script can be executed as a part of your build step so that it can write the result to some file like openapi-docs.json
.
The list of all supported types as of now is:
ZodAny
ZodArray
ZodBoolean
ZodDate
ZodDefault
ZodDiscriminatedUnion
discriminator
mapping when all Zod objects in the union are registered with .register()
or contain a refId
.ZodEffects
ZodEnum
ZodIntersection
ZodLiteral
ZodNativeEnum
ZodNullable
ZodNumber
z.number().int()
being inferred as type: 'integer'
ZodObject
.catchall
resulting in the respective additionalProperties
schemaZodOptional
ZodPipeline
ZodRecord
ZodString
format
for .datetime()
, .uuid()
, .email()
and .url()
and pattern
for .regex()
is also supportedZodTuple
ZodUnion
ZodUnknown
Extending an instance of ZodObject
is also supported and results in an OpenApi definition with allOf
In case you try to create an OpenAPI schema from a zod schema that is not one of the aforementioned types then you'd receive an UnknownZodTypeError
.
You can still register such schemas on your own by providing a type
via the .openapi
method. In case you think that the desired behavior can be achieved automatically do not hesitate to reach out to us by describing your case via Github Issues.
z.nullable(schema)
does not generate a $ref for underlying registered schemas.schema.nullable()
which has the exact same effect zod
wise but it is also fully supported on our end.FAQs
Builds OpenAPI schemas from Zod schemas
The npm package @asteasolutions/zod-to-openapi receives a total of 259,638 weekly downloads. As such, @asteasolutions/zod-to-openapi popularity was classified as popular.
We found that @asteasolutions/zod-to-openapi demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm has a revamped search experience with new, more transparent sorting options—Relevance, Downloads, Dependents, and Publish Date.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.