Zod to OpenAPI

A library that generates OpenAPI (Swagger) docs from Zod schemas

README

Zod to OpenAPI


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

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. Usingzod-to-openapi, we generate OpenAPI definitions directly from our zod schemas, thus having a single source of truth.

Simply put, it turns this:

  1. ```ts
  2. const UserSchema = z
  3.   .object({
  4.     id: z.string().openapi({ example: '1212121' }),
  5.     name: z.string().openapi({ example: 'John Doe' }),
  6.     age: z.number().openapi({ example: 42 }),
  7.   })
  8.   .openapi('User');

  9. registry.registerPath({
  10.   method: 'get',
  11.   path: '/users/{id}',
  12.   summary: 'Get a single user',
  13.   request: {
  14.     params: z.object({ id: z.string() }),
  15.   },

  16.   responses: {
  17.     200: {
  18.       description: 'Object with user data.',
  19.       content: {
  20.         'application/json': {
  21.           schema: UserSchema,
  22.         },
  23.       },
  24.     },
  25.   },
  26. });
  27. ```

into this:

  1. ```yaml
  2. components:
  3.   schemas:
  4.     User:
  5.       type: object
  6.       properties:
  7.         id:
  8.           type: string
  9.           example: '1212121'
  10.         name:
  11.           type: string
  12.           example: John Doe
  13.         age:
  14.           type: number
  15.           example: 42
  16.       required:
  17.         - id
  18.         - name
  19.         - age

  20. /users/{id}:
  21.   get:
  22.     summary: Get a single user
  23.     parameters:
  24.       - in: path
  25.         name: id
  26.         schema:
  27.           type: string
  28.         required: true
  29.     responses:
  30.       '200':
  31.         description: Object with user data
  32.         content:
  33.           application/json:
  34.             schema:
  35.               $ref: '#/components/schemas/User'
  36. ```

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

Usage


Installation


  1. ```shell
  2. npm install @asteasolutions/zod-to-openapi
  3. # or
  4. yarn add @asteasolutions/zod-to-openapi
  5. ```

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("")` - this way we specify that the underlying zod schema should be "registered" i.e added into `components/schemas` with the provided ``3. `.openapi("", { [key]: value })` - this unites the two use cases above so that we can specify both a registration `` and additional metadata

For 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.

  1. ```ts
  2. import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
  3. import { z } from 'zod';

  4. extendZodWithOpenApi(z);

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

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.

  1. ```ts
  2. import {
  3.   OpenAPIRegistry,
  4.   OpenApiGeneratorV3,
  5. } from '@asteasolutions/zod-to-openapi';

  6. const registry = new OpenAPIRegistry();

  7. // Register definitions here

  8. const generator = new OpenApiGeneratorV3(registry.definitions);

  9. return generator.generateComponents();
  10. ```

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:

  1. ```ts
  2. z.string().nullable().openapi(refId: 'name');
  3. ```

  1. ```yml
  2. # 3.1.0
  3. # nullable is invalid in 3.1.0 but type arrays are invalid in previous versions
  4. name:
  5.   type:
  6.     - 'string'
  7.     - 'null'

  8. # 3.0.0
  9. name:
  10.   type: 'string'
  11.   nullable: true
  12. ```

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:

  1. ```ts
  2. const UserSchema = z
  3.   .object({
  4.     id: z.string().openapi({ example: '1212121' }),
  5.     name: z.string().openapi({ example: 'John Doe' }),
  6.     age: z.number().openapi({ example: 42 }),
  7.   })
  8.   .openapi('User');

  9. const generator = new OpenApiGeneratorV3([UserSchema]);
  10. ```

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

  1. ```ts
  2. const UserSchema = registry.register(
  3.   'User',
  4.   z.object({
  5.     id: z.string().openapi({ example: '1212121' }),
  6.     name: z.string().openapi({ example: 'John Doe' }),
  7.     age: z.number().openapi({ example: 42 }),
  8.   })
  9. );

  10. const generator = new OpenApiGeneratorV3(registry.definitions);
  11. ```

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

  1. ```yaml
  2. components:
  3.   schemas:
  4.     User:
  5.       type: object
  6.       properties:
  7.         id:
  8.           type: string
  9.           example: '1212121'
  10.         name:
  11.           type: string
  12.           example: John Doe
  13.         age:
  14.           type: number
  15.           example: 42
  16.       required:
  17.         - id
  18.         - name
  19.         - age
  20. ```

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.

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.

  1. ```ts
  2. registry.registerPath({
  3.   method: 'get',
  4.   path: '/users/{id}',
  5.   description: 'Get user data by its id',
  6.   summary: 'Get a single user',
  7.   request: {
  8.     params: z.object({
  9.       id: z.string().openapi({ example: '1212121' }),
  10.     }),
  11.   },
  12.   responses: {
  13.     200: {
  14.       description: 'Object with user data.',
  15.       content: {
  16.         'application/json': {
  17.           schema: UserSchema,
  18.         },
  19.       },
  20.     },
  21.     204: {
  22.       description: 'No content - successful operation',
  23.     },
  24.   },
  25. });
  26. ```

The YAML equivalent of the schema above would be:

  1. ```yaml
  2. '/users/{id}':
  3.   get:
  4.     description: Get user data by its id
  5.     summary: Get a single user
  6.     parameters:
  7.       - in: path
  8.         name: id
  9.         schema:
  10.           type: string
  11.           example: '1212121'
  12.         required: true
  13.     responses:
  14.       '200':
  15.         description: Object with user data.
  16.         content:
  17.           application/json:
  18.             schema:
  19.               $ref: '#/components/schemas/User'
  20.       '204':
  21.         description: No content - successful operation
  22. ```

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:

  1. ```ts
  2. const UserIdParam = registry.registerParameter(
  3.   'UserId',
  4.   z.string().openapi({
  5.     param: {
  6.       name: 'id',
  7.       in: 'path',
  8.     },
  9.     example: '1212121',
  10.   })
  11. );

  12. registry.registerPath({
  13.   ...
  14.   request: {
  15.     params: z.object({
  16.       id: UserIdParam
  17.     }),
  18.   },
  19.   responses: ...
  20. });
  21. ```

The YAML equivalent would be:

  1. ```yaml
  2. components:
  3.   parameters:
  4.     UserId:
  5.       in: path
  6.       name: id
  7.       schema:
  8.         type: string
  9.         example: '1212121'
  10.       required: true

  11. '/users/{id}':
  12.   get:
  13.     ...
  14.     parameters:
  15.       - $ref: '#/components/parameters/UserId'
  16.     responses: ...
  17. ```

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.

Generating the full document


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:

  1. ```ts
  2. return generator.generateDocument({
  3.   openapi: '3.0.0',
  4.   info: {
  5.     version: '1.0.0',
  6.     title: 'My API',
  7.     description: 'This is the API',
  8.   },
  9.   servers: [{ url: 'v1' }],
  10. });
  11. ```

Defining custom components


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


A full example code can be found here. And the YAML representation of its result - here

Using schemas vs a registry


Schemas are automatically being registered when referenced. That means that if you have a schema like:

  1. ```ts
  2. const schema = z.object({ key: z.string().openapi('Test') }).openapi('Object');
  3. ```

you'd have the following resulting structure:

  1. ```yaml
  2. components:
  3.   schemas:
  4.     Test:
  5.       type: 'string',
  6.     Object:
  7.       type: 'object',
  8.       properties:
  9.         key:
  10.           $ref: '#/components/schemas/Test'
  11.       required: ['key']
  12. ```

This does not require any usages of an OpenAPIRegistry instance.

However the same output can be achieved with the following code:

  1. ```ts
  2. const registry = new OpenAPIRegistry();
  3. const schema = registry.register(
  4.   'Object',
  5.   z.object({ key: z.string().openapi('Test') })
  6. );
  7. ```

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:

  1. ```ts
  2. // file1.ts
  3. export const Schema1 = ...

  4. // file2.ts
  5. export const Schema2 = ...

  6. new OpenApiGeneratorV3([Schema1, Schema2])
  7. ```

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:

  1. ```ts
  2. // registry.ts
  3. export const registry = new OpenAPIRegistry()

  4. // file1.ts
  5. export const Schema1 = registry.register(...)

  6. // file2.ts
  7. export const Schema2 = registry.register(...)

  8. new OpenApiGeneratorV3(registry.definitions)
  9. ```

Adding a NewSchema into file3.ts and using registry.register would NOT require you to do any changes to the generator constructor.

Conclusion


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.

Adding it as part of your build


In a file inside your project you can have a file like so:

  1. ```ts
  2. export const registry = new OpenAPIRegistry();

  3. export function generateOpenAPI() {
  4.   const config = {...}; // your config comes here

  5.   return new OpenApiGeneratorV3(schemas.definitions).generateDocument(config);
  6. }
  7. ```

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.

Zod schema types


Supported types


The list of all supported types as of now is:

- ZodAny
- ZodArray
- ZodBoolean
- ZodDate
- ZodDefault
- ZodDiscriminatedUnion
  - including discriminator mapping when all Zod objects in the union are registered with .register() or contain a refId.
- ZodEffects
- ZodEnum
- ZodIntersection
- ZodLiteral
- ZodNativeEnum
- ZodNullable
- ZodNumber
  - including z.number().int() being inferred as type: 'integer'
- ZodObject
  - including .catchall resulting in the respective additionalProperties schema
- ZodOptional
- ZodPipeline
- ZodRecord
- ZodString
  - adding format for .datetime(), .uuid(), .email() and .url() and pattern for .regex() is also supported
- ZodTuple
- ZodUnion
- ZodUnknown

Extending an instance of ZodObject is also supported and results in an OpenApi definition with allOf

Unsupported types


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.

Technologies