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-json-response-validator

v0.0.8

Published

Validates a json response against an OpenApi 3 specification

Downloads

4

Readme

openapi-json-response-validator

API that utilises the Node.js express-openapi-validator middleware to validate that JSON responses conform to an OpenAPI 3 specification.

The API will expose a REST micro service to perform the validation.

Table of contents


Prerequisites

openapi-json-response-validator is built with nodejs and has the following dependencies.

  • nodejs, the minimum supported LTS version is 8.9.0.

Install

npm install openapi-json-response-validator --save

initialise

To make use of the api you will first need to initialise it with an open api specification.

const { initialise } = require('openapi-json-response-validator')

let port

try {
    port = await initialise({ apiSpec: './api.yaml' })
} catch(err) {
    console.log('An error occurred while trying to initialise validator', err)
}

The options that can be provided on initialisation are below.

options

  • apiSpec: (required) Defines the file containing the open api 3 specification.
  • port: (optional) Defines the port to expose the micro service on. By default a random free port will be used. The port can also be defined using the OPENAPI_JSON_RESPONSE_VALIDATOR_PORT environment variable.

If initialisation is successful the port the micro service is exposed on will be returned.

If initialisation fails an error will be thrown.


dispose

Will stop the micro service if one has been exposed.

const { dispose } = require('openapi-json-response-validator')

dispose()

validateResponse

You will firstly need to successfully initialise before you can call validateResponse.

const axios = require('axios')
const { validateResponse } = require('openapi-json-response-validator')

// get the response from the endpoint that needs validating
const resposne = await axios.get('http://localhost/v1/pets')

if (response.status !== 200)
    throw new Error('That should not have happened')

// validate the response against the specification
try {
    const result = await validateResponse('GET', '/v1/pets', 200, response.headers, response.data)
    
    if (result.valid === true) {
        console.log('the response conforms to the schema')
    } else {
        console.log('validation failed', result.errors)
        throw new Error('Validation failed')
    }
} catch(err) {
    console.log('An error occurred while trying to validate a response', err)
}

The parameters that can be provided on initialisation are below.

options

  • method: (required) The http method.
  • path: (required) The request path.
  • statusCode: (required) The http status code.
  • headers: (optional) The response headers as an object.
  • json: (optional) Object or array.

Will throw an error if something went wrong


Validate Response Http Request

const axios = require('axios')
const { initialise } = require('openapi-json-response-validator')

const port = await initialise({ apiSpec: './api.yaml' })

// get the response from the endpoint that needs validating
const resposne = await axios.get('http://localhost/v1/pets')

if (response.status !== 200)
    throw new Error('That should not have happened')

// validate the response against the specification
try {
    const validationResponse = await axios.post(`http://localhost:${port}/validate-response`, {
        method: 'GET',
        path: '/v1/pets',
        statusCode: 200,            
        headers: response.headers,
        json: response.data
    })

    if (validationResponse.status === 200) {
        if (validationResponse.data.valid === true)
            console.log('Validation passed')
        else
            console.log('Validation failed', validationResponse.data.errors)
    } else {
        throw new Error('Something went wrong trying to validate the response')
    }    
    
} catch (err) {
    console.log(err)
}

assertThatResponseIsValid

You will firstly need to successfully initialise before you can call assertThatResponseIsValid.

const axios = require('axios')
const { assertThatResponseIsValid } = require('openapi-json-response-validator')

// get the response from the endpoint that needs validating
const resposne = await axios.get('http://localhost/v1/pets')

if (response.status !== 200)
    throw new Error('That should not have happened')

// validate the response against the specification
try {
    await assertThatResponseIsValid('GET', '/v1/pets', 200, response.headers, response.data)
} catch(err) {
    console.log('An error occurred while trying to validate a response', err)
}

The parameters that can be provided on initialisation are below.

options

  • method: (required) The http method.
  • path: (required) The request path.
  • statusCode: (required) The http status code.
  • headers: (optional) The response headers as an object.
  • json: (optional) Object or array.

Will throw an error if something went wrong


License

(The MIT License)

Copyright (c) 2021 Lee Crowe a.k.a. croweman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.