Registry / web-framework / express-oas-validator

express-oas-validator

JSON →
library3.0.1jsnpmunverified

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.

npm install express-oas-validator
INSTALL
IMPORT
SIG · EXPRESS-OAS-VALIDA
E
express-oas-validator
web-frameworkjavascriptv3.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

init
import { init } from 'express-oas-validator';
const init = require('express-oas-validator').init;
The 'init' function is the primary export used to create a validator instance. While CommonJS 'require' syntax works, ESM 'import' is standard for new projects, especially with TypeScript support since v3.0.1.
validateRequest
const { validateRequest } = init(swaggerDefinition);
validateRequest is a function returned by the 'init' factory function, not a direct export from the package. It acts as an Express middleware for request validation. Do not attempt to import it directly.
validateResponse
const { validateResponse } = init(swaggerDefinition);
validateResponse is a function returned by the 'init' factory function, not a direct export from the package. It is used to validate response payloads. Do not attempt to import it directly.

This example demonstrates how to set up `express-oas-validator` with an Express application, using `init` to get `validateRequest` and `validateResponse` middleware. It shows basic request body validation and response payload validation for two different routes against a simple OpenAPI definition, including error handling.

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}`); });
Debug
Known issues
breakingIn 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).
fix
Update your code to use `validateRequest` and `validateResponse` instead of `validate`. Ensure you destructure them from the object returned by `init()`.
affects: >=2.0.0
breakingVersion 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'.
fix
Review the full changelog on GitHub (`v2.0.2...v3.0.0`) when upgrading from v2 to v3 to understand all necessary code modifications. Updating is strongly recommended due to performance improvements.
affects: >=3.0.0
gotchaAlthough 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.
fix
Always install and configure `body-parser` middleware in your Express application before `express-oas-validator` for routes that require body validation (e.g., `app.use(bodyParser.json());`).
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: validate is not a function
Attempting to use the old `validate` method name from versions prior to 2.0.0, after upgrading to version 2.0.0 or higher.
fix
Rename `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: "openApiDef" parameter is required
The `init` function was called without providing a valid OpenAPI definition object as its first argument.
fix
Ensure you pass your OpenAPI/Swagger definition object to the `init` function: `init(yourSwaggerDefinitionObject)`.
ValidationError: request.body should have required property 'propertyName'
The incoming request body does not conform to the OpenAPI schema defined for the endpoint, specifically missing a required property.
fix
Check the client-side request payload to ensure it matches the schema defined in your OpenAPI documentation for that endpoint and verify `body-parser` is correctly configured.
ReferenceError: bodyParser is not defined
`body-parser` middleware is used in an Express application but has not been imported or installed.
fix
Install `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');`).
Upgrade
Version history
3.0.1latest on npm
Audit
Dependencies
body-parserrequiredRecommended for parsing request bodies to enable proper request body validation by the middleware.
Agent activity
11 hits · last 30 days
node
10
Resources
express-oas-validator — npm install express-oas-validator · libregistry