Express OpenAPI Validator
raw JSON →express-oas-validator is an Express.js middleware library designed for validating API requests and responses against an OpenAPI Specification (OAS) definition. The library, currently at stable version 3.0.1, provides two core functionalities: `validateRequest` for incoming request validation (body, headers, path, query parameters) and `validateResponse` for outgoing response payload validation. It differentiates itself by offering both request and response validation within the same middleware, unlike some alternatives that focus solely on requests. The library's `init` function allows developers to create multiple validator instances for different OpenAPI definitions within a single application. Recent updates, including v3.0.1, have added full TypeScript support, enhancing developer experience. While the release cadence is not strictly regular, major versions have introduced significant improvements and new features.
Common errors
error TypeError: validate is not a function ↓
validate() calls to validateRequest() for incoming requests and validateResponse() for outgoing responses. Remember these are obtained from the init() function: const { validateRequest, validateResponse } = init(swaggerDefinition); error Error: "openApiDef" parameter is required ↓
init function: init(yourSwaggerDefinitionObject). error ValidationError: request.body should have required property 'propertyName' ↓
body-parser is correctly configured. error ReferenceError: bodyParser is not defined ↓
body-parser via npm (npm install body-parser) and import it in your application file (import bodyParser from 'body-parser'; or const bodyParser = require('body-parser');). Warnings
breaking In version 2.0.0, the primary validation methods were renamed. The single `validate` method was split and renamed to `validateRequest` (for input validation) and `validateResponse` (for output validation). ↓
breaking Version 3.0.0 introduced significant changes, including unspecified breaking changes, which may require adjustments to your existing implementation. It also fixed an 'important performance issue'. ↓
gotcha Although an older changelog (v1.0.1) mentioned 'Remove deprecated body-parser', the library's current documentation (v3.x) still explicitly recommends using `body-parser` for request body validation. Failing to include `body-parser` middleware for parsing request bodies (e.g., JSON) will lead to validation errors as the `req.body` object will be empty. ↓
Install
npm install express-oas-validator yarn add express-oas-validator pnpm add express-oas-validator Imports
- init wrong
const init = require('express-oas-validator').init;correctimport { init } from 'express-oas-validator'; - validateRequest
const { validateRequest } = init(swaggerDefinition); - validateResponse
const { validateResponse } = init(swaggerDefinition);
Quickstart
import express from 'express';
import bodyParser from 'body-parser';
import { init } from 'express-oas-validator';
// Placeholder for your OpenAPI definition
const swaggerDefinition = {
openapi: '3.0.0',
info: { title: 'Example API', version: '1.0.0' },
paths: {
'/api/v1/songs': {
post: {
requestBody: {
required: true,
content: {
'application/json': {
schema: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }
}
}
},
responses: { '200': { description: 'Song saved' } }
}
},
'/api/v1/name': {
post: {
responses: { '200': { description: 'Hello World response', content: { 'text/plain': { schema: { type: 'string' } } } } }
}
}
}
};
const app = express();
const PORT = process.env.PORT || 3000;
// Ensure body-parser is configured for request body validation
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const { validateRequest, validateResponse } = init(swaggerDefinition);
// Middleware validator for requests
app.post('/api/v1/songs', validateRequest(), (req, res) => {
console.log('Received song:', req.body);
res.send('You saved a song!');
});
// Response validator
app.post('/api/v1/name', (req, res, next) => {
try {
// Example: validate a string response for status 200
validateResponse('Hello World!', req, 200);
return res.send('Hello World!');
} catch (error) {
// Ensure error handling for response validation failures
return next(error);
}
});
// Express default error handler for validation errors
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Validation Error:', err);
if (err.status) {
return res.status(err.status).json(err);
}
res.status(500).json({ status: 500, message: 'Internal Server Error', originalError: err.message });
});
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});