Gathering detailed insights and metrics for express-openapi-validate
Gathering detailed insights and metrics for express-openapi-validate
Gathering detailed insights and metrics for express-openapi-validate
Gathering detailed insights and metrics for express-openapi-validate
npm install express-openapi-validate
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
76 Stars
208 Commits
12 Forks
3 Watching
2 Branches
6 Contributors
Updated on 17 Sept 2024
TypeScript (95.92%)
JavaScript (4.08%)
Cumulative downloads
Total Downloads
Last day
-9.4%
3,184
Compared to previous day
Last week
0.5%
15,991
Compared to previous week
Last month
1.3%
66,621
Compared to previous month
Last year
34.1%
572,374
Compared to previous year
6
23
Express middleware to validate requests based on an OpenAPI 3.0 document. OpenAPI specification was called the Swagger specification before version 3.
Install this package with npm or yarn:
1npm install --save express-openapi-validate 2# or 3yarn add express-openapi-validate
Then use the validator like this:
index.js
1const fs = require("fs"); 2const express = require("express"); 3const { OpenApiValidator } = require("express-openapi-validate"); 4const jsYaml = require("js-yaml"); 5 6const app = express(); 7app.use(express.json()); 8 9const openApiDocument = jsYaml.safeLoad( 10 fs.readFileSync("openapi.yaml", "utf-8"), 11); 12const validator = new OpenApiValidator(openApiDocument); 13 14app.post("/echo", validator.validate("post", "/echo"), (req, res, next) => { 15 res.json({ output: req.body.input }); 16}); 17 18app.use((err, req, res, next) => { 19 const statusCode = err.statusCode || 500; 20 res.status(statusCode).json({ 21 error: { 22 name: err.name, 23 message: err.message, 24 data: err.data, 25 }, 26 }); 27}); 28 29const server = app.listen(3000, () => { 30 console.log("Listening on", server.address()); 31});
Or using match()
:
1// Apply to all requests 2app.use(validator.match()); 3 4// On each request validator.validate("post", "/echo") is called automatically, 5// if it has a matching specification in the OpenAPI schema 6app.post("/echo", (req, res, next) => { 7 res.json({ output: req.body.input }); 8});
openapi.yaml
1openapi: 3.0.1 2info: 3 title: Example API with a single echo endpoint 4 version: 1.0.0 5components: 6 schemas: 7 Error: 8 type: object 9 properties: 10 error: 11 type: object 12 properties: 13 name: 14 type: string 15 message: 16 type: string 17 data: 18 type: array 19 items: 20 type: object 21 required: 22 - name 23 - message 24 required: 25 - error 26 responses: 27 error: 28 description: Default error response with error object 29 content: 30 application/json: 31 schema: 32 $ref: "#/components/schemas/Error" 33paths: 34 /echo: 35 post: 36 description: Echo input back 37 requestBody: 38 content: 39 application/json: 40 schema: 41 type: object 42 properties: 43 input: 44 type: string 45 required: 46 - input 47 responses: 48 "200": 49 description: Echoed input 50 content: 51 application/json: 52 schema: 53 type: object 54 properties: 55 output: 56 type: string 57 default: 58 $ref: "#/components/responses/error"
nullable
field for handling properties that can be null is supported (See
OpenAPI fixed fields)format
including additional data type formats
(like int32 and bytes) defined by OpenAPI (See OpenAPI data
types and Ajv formats)schema
features that are supported for request bodies are also
supported for parametersrequired
field for marking parameters that must be given is supportedapplication/json
(See
content
under Request Body Object)deprecated
xml
content
and style
(only schema
is supported)class OpenApiValidator
1const { OpenApiValidator } = require("express-openapi-validate");
The main class of this package. Creates JSON schema validators for the given operations defined in the OpenAPI document. In the background Ajv is used to validate the request.
constructor(openApiDocument: OpenApiDocument, options: ValidatorConfig = {}))
Creates a new validator for the given OpenAPI document.
options
parameter is optional. It has the following optional fields:
1{ 2 ajvOptions: Ajv.Options; 3}
You can find the list of options accepted by Ajv from its
documentation. The formats
object passed to Ajv will be merged
with additional OpenAPI formats supported by this library.
validate(method: Operation, path: string): RequestHandler
Returns an express middleware function for the given operation. The operation matching the given method and path has to be defined in the OpenAPI document or this method throws.
The middleware validates the incoming request according to the parameters
and
requestBody
fields defined in the Operation
Object. If the validation fails the next
express
function is called with an
ValidationError
.
See the Parameter Object and Request Body Object sections of the OpenAPI specification for details how to define schemas for operations.
method
must be one of the valid operations of an OpenAPI Path Item
Object:
"get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"
.
RequestHandler
is an express middleware function with the signature
(req: Request, res: Response, next: NextFunction): any;
.
match(options: MatchOptions = { allowNoMatch: false }): RequestHandler
Returns an express middleware function which calls validate()
based on the
request method and path. Using this function removes the need to specify
validate()
middleware for each express endpoint individually.
match()
throws an error if matching route specification is not found. This
ensures all requests are validated.
Use match({ allowNoMatch: true})
if you want to skip validation for routes
that are not mentioned in the OpenAPI schema. Use with caution: It allows
requests to be handled without any validation.
The following examples achieve the same result:
1// Using validate() 2app.post("/echo", validator.validate("post", "/echo"), (req, res, next) => { 3 res.json({ output: req.body.input }); 4}); 5 6// Using match() 7app.use(validator.match()); 8app.post("/echo", (req, res, next) => { 9 res.json({ output: req.body.input }); 10});
validateResponse(method: Operation, path: string): (res: any) => void
Creates a function for the given operation that can be used to validate responses. Response validation is meant to be used in tests and not in production code. See below for example usage.
For documentation of the method
and path
parameters see
validate
.
res
is expected to have the shape
{ statusCode: number, body: {}, headers: {}}
. The statusCode
field can also
be called status
and the body
field can be called data
. This means that
response objects from most request libraries should work out of the box.
If validation fails the validation function throws a
ValidationError
. Otherwise it returns
undefined
.
Example usage when using Jest and SuperTest:
1import { OpenApiValidator } from "express-openapi-validate"; 2import fs from "fs"; 3import jsYaml from "js-yaml"; 4import request from "supertest"; 5import app from "./app"; 6 7const openApiDocument = jsYaml.safeLoad( 8 fs.readFileSync("openapi.yaml", "utf-8"), 9); 10const validator = new OpenApiValidator(openApiDocument); 11 12test("/echo responses", async () => { 13 const validateResponse = validator.validateResponse("post", "/echo"); 14 let res = await request(app).post("/echo").send({}); 15 expect(validateResponse(res)).toBeUndefined(); 16 17 res = await request(app).post("/echo").send({ input: "Hello!" }); 18 expect(validateResponse(res)).toBeUndefined(); 19});
class ValidationError extends Error
1const { ValidationError } = require("express-openapi-validate");
This error is thrown by OpenApiValidator#validate
when the request validation
fails. It contains useful information about why the validation failed in
human-readable format in the .message
field and in machine-readable format in
the .data
array.
You can catch this error in your express error handler and handle it specially. You probably want to log the validation error and pass the errors to the client.
message: string
Human-readable error message about why the validation failed.
statusCode: number = 400
This field is always set to 400
. You can check this field in your express
error handler to decide what status code to send to the client when errors
happen.
data: ErrorObject[]
Machine-readable array of validation errors. Ajv Error
Objects documentation contains a list of the fields in
ErrorObject
.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
Found 2/14 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
28 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More