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-validatorVerified import paths — ran on the pinned version, not inferred.
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.
Update your code to use `validateRequest` and `validateResponse` instead of `validate`. Ensure you destructure them from the object returned by `init()`.
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.
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());`).
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);`Ensure you pass your OpenAPI/Swagger definition object to the `init` function: `init(yourSwaggerDefinitionObject)`.
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.
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');`).