What is @asteasolutions/zod-to-openapi?
@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));