cdimascio / express-openapi-validator

๐Ÿฆ‹ Auto-validates api requests, responses, and securities using ExpressJS and an OpenAPI 3.x specification
MIT License
919 stars 211 forks source link
connect-middleware express express-middleware expressjs hacktoberfest middleware nodejs openapi openapi-validator openapi3 request-validation rest-api

๐Ÿฆ‹ express-openapi-validator

example workflow All Contributors Coverage Status Codacy Badge Gitpod Ready-to-Code

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:

Docs:

GitHub stars Twitter URL

NestJS Koa and Fastify now available! ๐Ÿš€

OAS 3.1 (experimental)

Install

npm install express-openapi-validator

# experimental OAS 3.1 in alpha (contributions welcome - see branch `oas-3.1` and pr-882 
# please provide feedback on (issue-573)
npm install express-openapi-validator@6.0.0-alpha.5

Usage

  1. Require/import the openapi validator
const OpenApiValidator = require('express-openapi-validator');

or

import * as OpenApiValidator from 'express-openapi-validator';
  1. Install the middleware
app.use(
  OpenApiValidator.middleware({
    apiSpec: './openapi.yaml',
    validateRequests: true, // (default)
    validateResponses: true, // false by default
  }),
);
  1. Register an error handler
app.use((err, req, res, next) => {
  // format error
  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.

Documentation

See the doc for complete documenation

deprecated legacy doc

License

MIT

Buy Me A Coffee