swagger-route-validator
TypeScript icon, indicating that this package has built-in type declarations

3.1.0 • Public • Published

logo
Swagger Route Validator



  • 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!

Usage

Request validation

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.

Response validation

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)}`);

Running tests

npm run test

Running benchmarks

npm run bench

Migration from 2.X to 3.X

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.

License

Apache 2.0 - Frederic Charette

/swagger-route-validator/

    Package Sidebar

    Install

    npm i swagger-route-validator

    Weekly Downloads

    24

    Version

    3.1.0

    License

    Apache-2.0

    Unpacked Size

    32.8 kB

    Total Files

    11

    Last publish

    Collaborators

    • fed135