OpenAPI-Enforcer
Tools for using the Open API Specification (OAS)
Supports OAS 2.0 (formerly Swagger) and OAS 3.x.x
Features
- Create an API.
- Validate your OAS documents.
- Serialize, deserialize, and validate values against OAS schemas.
- Identify the operation associated with a request.
- Parse, deserialize, and validate request parameters.
- Facilitated response building.
- Generate random valid values for a schema.
- Plugin environment for custom document validation and extended functionality including custom data type formats.
Installation
npm install openapi-enforcer
Examples
Loading and Validating a Document
Use the Enforcer to load and resolve all $ref values and then to validate the complete document.
const Enforcer = require('openapi-enforcer')
async function run () {
const [openapi, error, warning] = await Enforcer('./path/to/openapi.yml', {
fullResult: true
})
if (error !== undefined) console.error(error)
if (warning !== undefined) console.warn(warning)
if (openapi !== undefined) console.log('Document is valid')
}
run.catch(console.error)
Processing an Incoming Request
const Enforcer = require('openapi-enforcer')
async function run () {
const openapi = await Enforcer('./path/to/openapi.yml')
const [ req, error ] = openapi.request({
method: 'POST',
path: '/tasks',
body: { task: 'Buy Milk', quantity: 2 }
})
if (req.operaton.operationId === 'my-operation-id') {
}
}
run.catch(console.error)
Producing a Valid Result
const Enforcer = require('openapi-enforcer')
async function run () {
const openapi = await Enforcer('./path/to/openapi.yml')
const [ req ] = openapi.request({
method: 'POST',
path: '/tasks',
body: { task: 'Buy Milk', quantity: 2 }
})
const body = { id: 1, task: 'Buy Milk', quantity: 2, dateCompleted: null }
const headers = {}
const [ res, error ] = req.response(200, body, headers)
console.log(res.body, res.headers)
}
run.catch(console.error)