What is express-openapi-validator?
express-openapi-validator is a middleware for Express.js that validates API requests and responses against an OpenAPI 3.0 specification. It helps ensure that your API adheres to the defined contract, improving reliability and maintainability.
What are express-openapi-validator's main functionalities?
Request Validation
This feature validates incoming requests against the OpenAPI specification. If a request does not conform to the spec, an error is returned.
const express = require('express');
const OpenApiValidator = require('express-openapi-validator');
const app = express();
app.use(express.json());
app.use(
OpenApiValidator.middleware({
apiSpec: './api.yaml',
validateRequests: true,
})
);
app.post('/pets', (req, res) => {
res.json({ message: 'Pet added successfully' });
});
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Response Validation
This feature validates outgoing responses against the OpenAPI specification. If a response does not conform to the spec, an error is returned.
const express = require('express');
const OpenApiValidator = require('express-openapi-validator');
const app = express();
app.use(express.json());
app.use(
OpenApiValidator.middleware({
apiSpec: './api.yaml',
validateResponses: true,
})
);
app.get('/pets', (req, res) => {
res.json([{ id: 1, name: 'Fluffy' }]);
});
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Security Validation
This feature validates security requirements defined in the OpenAPI specification. It ensures that requests meet the necessary security criteria, such as API keys or OAuth tokens.
const express = require('express');
const OpenApiValidator = require('express-openapi-validator');
const app = express();
app.use(express.json());
app.use(
OpenApiValidator.middleware({
apiSpec: './api.yaml',
validateSecurity: true,
})
);
app.get('/secure-endpoint', (req, res) => {
res.json({ message: 'Secure data' });
});
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Other packages similar to express-openapi-validator
swagger-express-middleware
swagger-express-middleware is a similar package that provides middleware for Express.js to handle Swagger (OpenAPI) documents. It offers request validation, mock responses, and more. Compared to express-openapi-validator, it is more focused on Swagger 2.0 and provides additional features like mock responses.
openapi-backend
openapi-backend is a framework-agnostic library for building and validating APIs based on OpenAPI specifications. It provides request validation, response validation, and routing. Unlike express-openapi-validator, it is not tied to Express.js and can be used with other frameworks or even standalone.
ajv
ajv (Another JSON Schema Validator) is a JSON schema validator that can be used to validate data against JSON schemas, including OpenAPI schemas. While it is not specifically designed for Express.js or OpenAPI, it can be integrated into an Express.js application for similar validation purposes. It offers high performance and extensive features for JSON schema validation.
๐ฆ express-openapi-validator
An OpenApi validator for ExpressJS that automatically validates API requests and responses using an OpenAPI 3 specification.
๐ฆexpress-openapi-validator is an unopinionated library that integrates with new and existing API applications. express-openapi-validator lets you write code the way you want; it does not impose any coding convention or project layout. Simply, install the validator onto your express app, point it to your OpenAPI 3 specification, then define and implement routes the way you prefer. See an example.
Features:
- โ๏ธ request validation
- โ๏ธ response validation (json only)
- ๐ฎ security validation / custom security functions
- ๐ฝ 3rd party / custom formats / custom data serialization-deserialization
- ๐งต optionally auto-map OpenAPI endpoints to Express handler functions
- โ๏ธ $ref support; split specs over multiple files
- ๐ file upload
Docs:
NestJS
Koa and Fastify now available! ๐
Install
npm install express-openapi-validator
Usage
- Require/import the openapi validator
const OpenApiValidator = require('express-openapi-validator');
or
import * as OpenApiValidator from 'express-openapi-validator';
- Install the middleware
app.use(
OpenApiValidator.middleware({
apiSpec: './openapi.yaml',
validateRequests: true,
validateResponses: true,
}),
);
- Register an error handler
app.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message,
errors: err.errors,
});
});
Important: Ensure express is configured with all relevant body parsers. Body parser middleware functions must be specified prior to any validated routes. See an example.
See the wiki for complete documenation
License
MIT