What is @anatine/zod-openapi?
@anatine/zod-openapi is an npm package that bridges the gap between Zod, a TypeScript-first schema declaration and validation library, and OpenAPI, a standard for defining RESTful APIs. This package allows developers to generate OpenAPI documentation from Zod schemas, making it easier to maintain API documentation in sync with the actual code.
What are @anatine/zod-openapi's main functionalities?
Generate OpenAPI Schema from Zod Schema
This feature allows you to generate an OpenAPI schema from a Zod 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('@anatine/zod-openapi');
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
const openApiSchema = openApi({
title: 'User API',
version: '1.0.0',
schemas: {
User: UserSchema
}
});
console.log(JSON.stringify(openApiSchema, null, 2));
Add Metadata to Zod Schemas
This feature allows you to add OpenAPI metadata directly to Zod schemas. The code sample shows how to extend Zod with OpenAPI capabilities and add descriptions to the fields in a User schema.
const { z } = require('zod');
const { extendZodWithOpenApi } = require('@anatine/zod-openapi');
extendZodWithOpenApi(z);
const UserSchema = z.object({
id: z.string().openapi({ description: 'User ID' }),
name: z.string().openapi({ description: 'User Name' }),
email: z.string().email().openapi({ description: 'User Email' })
});
console.log(UserSchema.openapi);
Generate OpenAPI Documentation
This feature allows you to generate a full OpenAPI documentation from Zod schemas. The code sample demonstrates how to define a Zod schema, convert it to an OpenAPI schema, and then generate the full OpenAPI documentation.
const { z } = require('zod');
const { openApi, generateOpenApiDocument } = require('@anatine/zod-openapi');
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
const openApiSchema = openApi({
title: 'User API',
version: '1.0.0',
schemas: {
User: UserSchema
}
});
const openApiDocument = generateOpenApiDocument(openApiSchema);
console.log(JSON.stringify(openApiDocument, null, 2));
Other packages similar to @anatine/zod-openapi
zod-to-openapi
zod-to-openapi is another package that converts Zod schemas to OpenAPI documentation. It offers similar functionality to @anatine/zod-openapi but may have different API design and additional features. It is a good alternative if you are looking for different options in the same space.
ts-json-schema-generator
ts-json-schema-generator generates JSON schema from TypeScript types. While it does not directly generate OpenAPI documentation, JSON schema can be used as a base for OpenAPI schemas. This package is useful if you are working with TypeScript and need to generate schemas for validation or documentation purposes.
openapi-typescript
openapi-typescript generates TypeScript types from OpenAPI schemas. It works in the opposite direction compared to @anatine/zod-openapi, but it can be useful in a workflow where you start with OpenAPI documentation and want to generate TypeScript types for use in your application.
@anatine/graphql-zod-validation
Fork for type support
This codebase is taken direction from GraphQL code generator
Used to generate validation schema from the following libraries.
NOTE
This module has additional support for generating type
objects from GraphQL
Useful when using the expected validation type (or one extended) to validate data before returning to your resolver.
Quick Start
Start by installing this plugin and write simple plugin config;
npm i @anatine/graphql-zod-validation
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
strictScalars: true
schema: yup
You can check example directory if you want to see more complex config example or how is generated some files.
The Q&A for each schema is written in the README in the respective example directory.
Config API Reference
schema
type: ValidationSchema
default: 'yup'
Specify generete validation schema you want.
You can specify yup
or zod
or myzod
.
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
schema: yup
importFrom
type: string
When provided, import types from the generated typescript types file path. if not given, omit import statement.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { GeneratedInput } from './graphql'
typesPrefix
type: string
default: (empty)
Prefixes all import types from generated typescript type.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
typesPrefix: I
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { IGeneratedInput } from './graphql'
typesSuffix
type: string
default: (empty)
Suffixes all import types from generated typescript type.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
typesSuffix: I
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { GeneratedInputI } from './graphql'
enumsAsTypes
type: boolean
default: false
Generates enum as TypeScript type
instead of enum
.
notAllowEmptyString
type: boolean
default: false
Generates validation string schema as do not allow empty characters by default.
scalarSchemas
type: ScalarSchemas
Extends or overrides validation schema for the built-in scalars and custom GraphQL scalars.
useObjectTypes
type: boolean
default: false
When enabled, object types type
will also be converted via codegen.
yup schema
config:
schema: yup
scalarSchemas:
Date: yup.date()
Email: yup.string().email()
zod schema
config:
schema: zod
useObjectTypes: true
scalarSchemas:
Date: z.date()
Email: z.string().email()
directives
type: DirectiveConfig
Generates validation schema with more API based on directive schema. For example, yaml config and GraphQL schema is here.
input ExampleInput {
email: String! @required(msg: "Hello, World!") @constraint(minLength: 50, format: "email")
message: String! @constraint(startsWith: "Hello")
}
yup schema extended
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
schema: yup
directives:
required:
msg: required
constraint:
minLength: min
startsWith: ["matches", "/^$1/"]
format:
email: email
Then generates yup validation schema like below.
export function ExampleInputSchema(): yup.SchemaOf<ExampleInput> {
return yup.object({
email: yup.string().defined().required("Hello, World!").min(50).email(),
message: yup.string().defined().matches(/^Hello/)
})
}
zod schema extended
generates:
path/to/graphql.ts:
plugins:
- typescript
- typescript-validation-schema
config:
schema: zod
directives:
constraint:
minLength: min
startsWith: ["regex", "/^$1/", "message"]
format:
email: email
Then generates zod validation schema like below.
export function ExampleInputSchema(): z.ZodSchema<ExampleInput> {
return z.object({
email: z.string().min(50).email(),
message: z.string().regex(/^Hello/, "message")
})
}
other schema
Please see example directory.