openapi-express
v0.0.7
Published
Typesafe Express Router wrapper supporting OpenAPI types
Downloads
391
Readme
Status: Experimental
openapi-express
is a typesafe Express Router wrapper supporting OpenAPI types.
- Typesafe: Build with TypeScript for strong type safety and support for
openapi-typescript
types - Validation: Ensures request validation against defined schemas using
zod
Motivation
Provide a typesafe, straightforward, and lightweight wrapper for the Express Router that seamlessly integrates with OpenAPI schemas using openapi-typescript
. It aims to simplify error handling and request validation.
📖 Usage
1. Generate TypeScript Definitions
Use openapi-typescript
to generate TypeScript definitions from your OpenAPI schema.
npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts
2. Create an OpenAPI Router
Import the generated paths
and use createOpenApiRouter()
to create an OpenAPI router.
router.ts
import { createOpenApiRouter } from 'openapi-express';
import { paths } from './openapi-paths'; // Import generated paths
export const router: Router = Router();
export const openApiRouter = createOpenApiRouter<paths>(router);
3. Use the Router in an Express App
Integrate the OpenAPI router into your Express application to handle requests. Use express.json()
middleware to parse incoming JSON requests.
app.ts
import express from 'express';
import { router } from './router';
const app = express();
app.use(express.json()); // For parsing application/json
app.use('/', router);
4. Define the Endpoints with Full Type Safety
Define your API endpoints with full type safety and request validation using Zod. TypeScript provides type safety at compile time, but runtime validation is necessary to ensure incoming requests meet the expected structure and types. Zod helps with this by providing a schema-based validation mechanism. If a schema is invalid, a ValidationError
is thrown.
routes/posts.ts
import { Router } from 'express';
import { z } from 'zod';
import { openApiRouter } from '../router';
const posts = [
{ id: '1', title: 'First Post', content: 'This is the first post.' },
{ id: '2', title: 'Second Post', content: 'This is the second post.' }
];
// Get all posts
openApiRouter.get(
'/posts',
{},
async (req, res) => {
res.json(posts);
}
);
// Get a post by ID
openApiRouter.get(
'/posts/{id}',
{
pathSchema: {
id: z.string()
}
},
async (req, res) => {
const post = posts.find(p => p.id === req.params.id);
if (post) {
res.json(post);
} else {
res.status(404).json({ message: 'Post not found' });
}
}
);
// Create a new post
openApiRouter.post(
'/posts',
{
bodySchema: z.object({
title: z.string(),
content: z.string()
})
},
async (req, res) => {
const newPost = {
id: (posts.length + 1).toString(),
...req.body
};
posts.push(newPost);
res.status(201).json(newPost);
}
);