- The fastest request/response validator for OpenAPI applications
- Zero dependencies ⭐
- Battle-tested by Fortune 500 companies
- Supports OpenAPI 3.X features like $ref, $not, $anyOf, $allOf, $oneOf, etc.
- Supports most common data formats like emails, ips, uuids, dates, etc.
- Supports Express 4.x and 5.x
- Uses OpenAPI/ Swagger specs as Objects. Say goodbye to YAML files!
SRV offers a built-in express middleware for easy integration:
import {expressRequestValidation} from 'swagger-route-validator';
import express from 'express';
const app = express();
app.get('/foo', expressRequestValidation(/* An object of the route's spec */, /* The full spec */), (req, res, next) => {
res.send('Hello World!');
});
You may also run validations directly:
import {validateRequest} from 'swagger-route-validator';
const errors = validateRequest(/* An object of the route's spec */, req, /* The full spec */);
if (errors.length > 0) throw new Error(`Request object does not match the specification for this route: ${JSON.stringify(errors)}`);
Finally, if you want to put the validation middleware earlier in the stack (before routing) you could follow this example. The middleware will try to match the request to a route from the spec. This could be used to retrospec an old API, but it is not recommenced for new services.
SRV also offers a middleware for response validation:
import {expressResponseValidation} from 'swagger-route-validator';
import express from 'express';
const app = express();
app.get('/foo', expressResponseValidation(/* An object of the route's spec */, { behavior: 'error' }, /* The full spec */), (req, res, next) => {
res.send('Hello World!');
});
As well as a direct validation function:
import {validateResponse} from 'swagger-route-validator';
const errors = validateResponse(/* An object of the route's spec */, body, res, /* The full spec */);
if (errors.length > 0) throw new Error(`Response object does not match the specification for this route: ${JSON.stringify(errors)}`);
npm run test
npm run bench
SRV no longer has a default export, your import statement will need to change from:
import validate from 'swagger-route-validator';
To:
import {validateRequest} from 'swagger-route-validator';
SRV will now also throw errors when meet with a malformed spec Object.
Apache 2.0 - Frederic Charette