https://github.com/matteopolak/express-zod-openapi-router
A drop-in replacement for Express.js Router with input validation and OpenAPI schema generation
https://github.com/matteopolak/express-zod-openapi-router
Last synced: 2 months ago
JSON representation
A drop-in replacement for Express.js Router with input validation and OpenAPI schema generation
- Host: GitHub
- URL: https://github.com/matteopolak/express-zod-openapi-router
- Owner: matteopolak
- Created: 2024-08-09T00:53:34.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2024-08-11T02:23:51.000Z (10 months ago)
- Last Synced: 2025-02-18T08:53:55.580Z (4 months ago)
- Language: TypeScript
- Homepage:
- Size: 275 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
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](https://zod.dev)
- Generate OpenAPI documentation from route definitions and Zod schemas## Installation
```bash
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](./examples) directory.
```typescript
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, only `string` and `string[]`.