Security News
Supply Chain Attack Detected in @solana/web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
@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 at Astea Solutions made this library because of the duplication of work when creating a documentation for an API that uses zod
to validate request input and output.
npm install @asteasolutions/zod-to-openapi
# or
yarn add @asteasolutions/zod-to-openapi
In order to specify some OpenAPI specific metadata you should use the exported extendZodWithOpenApi
function with your own instance of zod
.
Note: This should be done only once in a common-entrypoint file of your project (for example an index.ts
/app.ts
)
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
class is used as a utility for creating definitions that are then to be used to
generate the OpenAPI document using the OpenAPIGenerator
class. In order to generate components the generateComponents
method should be used.
import {
OpenAPIRegistry,
OpenAPIGenerator,
} from '@asteasolutions/zod-to-openapi';
const registry = new OpenAPIRegistry();
// Register definitions here
const generator = new OpenAPIGenerator(registry.definitions);
return generator.generateComponents();
An OpenAPI schema should be registered using the register
method of an OpenAPIRegistry
instance.
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,
}),
})
);
The YAML equivalent of the schema above would be:
User:
type: object
properties:
id:
type: string
example: '1212121'
name:
type: string
example: John Doe
age:
type: number
example: 42
required:
- id
- name
- age
Note: All properties defined inside .openapi
of a single zod schema are applied at their appropriate schema level.
The result would be an object like { components: { schemas: { User: {...} } } }
. The key for the object is the value of the first argument passed to .register
(in this case - User
).
The resulting schema can then be referenced by using $ref: #/components/schemas/User
in an existing OpenAPI JSON.
An OpenAPI parameter (query/path/header) should be registered using the registerParameter
method of an OpenAPIRegistry
instance.
const UserIdSchema = registry.registerParameter(
'UserId',
z.string().openapi({
param: {
name: 'id',
in: 'path',
},
example: '1212121',
})
);
Note: Parameter properties are more specific to those of an OpenAPI schema. 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.
The YAML equivalent of the schema above would be:
UserId:
in: path
name: id
schema:
type: string
example: '1212121'
required: true
The result would be an object like { components: { parameters: { UserId: {...} } } }
. The key for the object is the value of the first argument passed to .registerParameter
(in this case - UserId
).
The resulting schema can then be referenced by using $ref: #/components/parameters/UserId
in an existing OpenAPI JSON.
A full OpenAPI document can be generated using the generateDocument
method of an OpenAPIGenerator
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' }],
});
An OpenAPI path should be registered using the registerPath
method of an OpenAPIRegistry
instance.
registry.registerPath({
method: 'get',
path: '/users/{id}',
description: 'Get user data by its id',
summary: 'Get a single user',
request: {
params: z.object({ id: UserIdSchema }),
},
responses: {
200: {
mediaType: 'application/json',
schema: UserSchema.openapi({
description: 'Object with user data.',
}),
},
204: z.void(),
},
});
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
- being any zod
instanceheaders
- an array of zod
instancesresponses
- an object where the key is the status code or default
and the value is either:
ZodVoid
- meaning a no content responsemediaType
(a string like application/json
) and a schema
of any zod typeA full example code can be found here. And the YAML representation of its result - here
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 OpenAPIGenerator(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 can execute 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
.
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
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.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.