express-zod-openapi-router
v0.0.2
Published
A thin wrapper around Express to validate requests and generate OpenAPI documentation.
Downloads
4
Readme
Express Zod OpenAPI Router
A thin wrapper around Express to validate requests and generate OpenAPI documentation.
Features
- Drop-in replacement for Express.js
Router
- Validate request bodies and query parameters with Zod
- Generate OpenAPI documentation from route definitions and Zod schemas
Installation
npm install express-zod-openapi
pnpm add express-zod-openapi
Example
Examples can be run with EXAMPLE={name} pnpm example
, see more examples in the examples directory.
import express from 'express';
import { z } from 'zod';
import { createDocument, operation, Router } from 'express-zod-openapi-router';
const app = express();
const router = Router();
app.use(express.json());
app.use(router);
const Query = z.object({
name: z.string().default('world').openapi({
description: 'The name to say hello to',
example: 'John Smith'
}),
});
router.get('/hello', operation({
summary: 'Say hello',
description: 'Say hello to the world',
query: Query,
}, (req, res) => {
res.json({ message: `Hello, ${req.query.name}!` });
// ^^^^^ { name: string }
}));
const document = createDocument({
title: 'Hello World',
version: '1.0.0',
servers: [{ url: 'http://localhost:3000' }],
}, router);
app.use('/openapi.json', (req, res) => {
res.json(document);
});
app.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});
Limitations
- Only supports
application/json
bodies for documentation. However, other content types can be validated against by implementing middleware that transforms the body into an object of the right shape. - Does not support
RegExp
paths, onlystring
andstring[]
.