npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-openapi-validate

v0.6.1

Published

Express middleware to validate request based on an OpenAPI 3 document

Downloads

67,416

Readme

express-openapi-validate

codecov npm Try on RunKit

Express middleware to validate requests based on an OpenAPI 3.0 document. OpenAPI specification was called the Swagger specification before version 3.

Usage

Install this package with npm or yarn:

npm install --save express-openapi-validate
# or
yarn add express-openapi-validate

Then use the validator like this:

index.js

const fs = require("fs");
const express = require("express");
const { OpenApiValidator } = require("express-openapi-validate");
const jsYaml = require("js-yaml");

const app = express();
app.use(express.json());

const openApiDocument = jsYaml.safeLoad(
  fs.readFileSync("openapi.yaml", "utf-8"),
);
const validator = new OpenApiValidator(openApiDocument);

app.post("/echo", validator.validate("post", "/echo"), (req, res, next) => {
  res.json({ output: req.body.input });
});

app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    error: {
      name: err.name,
      message: err.message,
      data: err.data,
    },
  });
});

const server = app.listen(3000, () => {
  console.log("Listening on", server.address());
});

Or using match():

// Apply to all requests
app.use(validator.match());

// On each request validator.validate("post", "/echo") is called automatically,
// if it has a matching specification in the OpenAPI schema
app.post("/echo", (req, res, next) => {
  res.json({ output: req.body.input });
});

openapi.yaml

openapi: 3.0.1
info:
  title: Example API with a single echo endpoint
  version: 1.0.0
components:
  schemas:
    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            name:
              type: string
            message:
              type: string
            data:
              type: array
              items:
                type: object
          required:
            - name
            - message
      required:
        - error
  responses:
    error:
      description: Default error response with error object
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
paths:
  /echo:
    post:
      description: Echo input back
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                input:
                  type: string
              required:
                - input
      responses:
        "200":
          description: Echoed input
          content:
            application/json:
              schema:
                type: object
                properties:
                  output:
                    type: string
        default:
          $ref: "#/components/responses/error"

Supported features

Currently unsupported features

Public API

class OpenApiValidator

const { 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:

{
  ajvOptions: Ajv.Options;
}

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:

// Using validate()
app.post("/echo", validator.validate("post", "/echo"), (req, res, next) => {
  res.json({ output: req.body.input });
});

// Using match()
app.use(validator.match());
app.post("/echo", (req, res, next) => {
  res.json({ output: req.body.input });
});

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:

import { OpenApiValidator } from "express-openapi-validate";
import fs from "fs";
import jsYaml from "js-yaml";
import request from "supertest";
import app from "./app";

const openApiDocument = jsYaml.safeLoad(
  fs.readFileSync("openapi.yaml", "utf-8"),
);
const validator = new OpenApiValidator(openApiDocument);

test("/echo responses", async () => {
  const validateResponse = validator.validateResponse("post", "/echo");
  let res = await request(app).post("/echo").send({});
  expect(validateResponse(res)).toBeUndefined();

  res = await request(app).post("/echo").send({ input: "Hello!" });
  expect(validateResponse(res)).toBeUndefined();
});

class ValidationError extends Error

const { 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.