Generate OpenAPI documentation from Zod schemas
masterThe zod-to-openapi library allows you to use Zod schemas as a single source of truth for both runtime validation and OpenAPI (Swagger) documentation. By extending Zod schemas with .openapi() metadata, you can define examples, descriptions, and component names that are then used to generate a complete OpenAPI specification.
This eliminates the need to maintain separate validation logic and documentation files, ensuring they stay in sync.
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,
},
},
},
},
});