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

openapi-contract-validator

v1.0.0

Published

Validate JSON requests & responses against OpenAPI Schemas

Downloads

9

Readme

Openapi contract validator

A contract compliance validator for OpenAPI Schemas. Validate a request-response pair against an OpenAPI Schema.

Note: This is not a validator for the OpenAPI Schemas (OAS) themselves. This package uses an OAS to validate a request-response pair against the truth of the OAS.

Note: Not intended or optimized for production environments.

If you're not familiar with Node you're probably not the intended audience for this package. This package contains the validator itself for integration into Javascript-based test frameworks. If you're using a non-js framework you're looking for the language agnostic openapi-contract-validator-server.

Installation

npm install openapi-contract-validator

Supported versions

| OpenAPI Schema version | Supported | | ---------------------- | :-------: | | 1.0 (Swagger) | ❌ | | 2.0 (Swagger) | ❌ | | 3.0.x | ✔️ |

Usage

TL;DR:

const {Http, Validator} = require('openapi-contract-validator');

const oas = 'path/to/your/openapi-schema.yaml';

const http = new Http();
http.request.baseUrl = 'http://localhost:8080';
http.request.endpoint = '/api/test';
http.request.method = 'GET';

http.response.statusCode = '200';
http.response.headers = {...};
http.response.body = {...};

const validator = new Validator();
const options = {};

validator
    .validate(oas, http, options)
    .then(() => {
        console.log('Validation passed •‿•');
    })
    .catch((error) => {
        console.error('Validation failed (╯°□°)╯︵ ┻━┻');
        throw error;
    });

Importing

First, require the OAS validator itself:

// Require syntax
const {Http, Validator} = require('openapi-contract-validator');
// Import syntax
import {Http, Validator} from 'openapi-contract-validator';

Define a contract

Before we can validate a request-response pair we'll have to define what is correct. This is documented in an OpenAPI Schema.

Provide the OAS in one of the following ways:

  1. An absolute path to the OAS file. Valid file extensions are .json, .js, .yaml, and .yml.

    const oas = 'absolute/path/to/your/openapi-schema.yaml';
  2. An object of paths to the OAS file with a default. The file under default will always be used.

    const oas = {
        default: 'absolute/path/to/your/openapi-schema.json',
        subSchema: 'absolute/path/to/your/openapi-subschema.yaml',
    };
  3. A parsed OAS as an object.

    const oas = {
        openapi: '3.0.2',
        // ...
    };

Detail the HTTP interaction

An HTTP interaction consists of two parts: The request and the response. In order to make oas-validator more library-agnostic I've opted to create an intermediary data structure. Create an instance of Http and add details to it.

const http = new Http();
http.request.baseUrl = 'http://localhost:8080';
http.request.endpoint = '/api/test';
http.request.method = 'GET';

http.response.statusCode = '200';
http.response.headers = {...};
http.response.body = {...};

Validation

The final step is to bring everything together and do the actual validation.

const validator = new Validator();
const options = {};

validator
    .validate(oas, http, options)
    .then(() => {
        console.log('Validation passed •‿•');
    })
    .catch((error) => {
        console.error('Validation failed (╯°□°)╯︵ ┻━┻');
        throw error;
    });

Options

All validator options are optional.

| Option | Default | Description | | ------------------ | ----------------------- | ------------------------------------------------------------ | | endpoint | http.request.endpoint | The endpoint as specified in the OpenAPI schema | | method | http.request.method | The HTTP method for the endpoint as specified in the OpenAPI schema | | statusCode | http.response.method | The status code for the HTTP method as specified in the OpenAPI schema | | requireAllFields | false | Mark all fields in the OpenAPI schema as required | | concatArrays | false | Merge content of arrays into a single value or object | | allowEmptyString | false | Allow empty strings and strings that only contain whitespace |

// Full options object with default values
const options = {
    endpoint: http.request.endpoint,
    method: http.request.method,
    statusCode: http.response.statusCode,
    requireAllFields: false,
    concatArrays: false,
    allowEmptyString: false,
};

Contributing

Contributors are always welcome! I really don't care if you are a beginner or an expert, all help is welcome. Help includes code contributions, fixing one of my many typos, helping others, etc.