JSPM

  • Created
  • Published
  • Downloads 46943
  • Score
    100M100P100Q140443F
  • License MIT

Non-opinionated middleware tools for building APIs with the OpenAPI standard in your favourite backend or framework like Express, Hapi, Azure Functions or AWS Lambda. Includes routing, validation and mocking functionality.

Package Exports

  • openapi-backend

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (openapi-backend) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

OpenAPI Backend

Build Status npm version License Sponsored

Non-opinionated middleware tools for building APIs with the OpenAPI standard in your favourite Node.js backends and frameworks.

Includes routing, validation and mocking functionality.

Features

(Currently only OpenAPI v3.0.0+ is supported)

Documentation

See DOCS.md

Quick Start

Full example projects included in the repo

npm install --save openapi-backend
import OpenAPIBackend from 'openapi-backend';

const api = new OpenAPIBackend({
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'My API',
      version: '1.0.0',
    },
    paths: {
      '/pets': {
        get: {
          operationId: 'getPets',
          responses: {
            200: { description: 'ok' },
          },
        },
      },
      '/pets/{id}': {
        get: {
          operationId: 'getPetById',
          responses: {
            200: { description: 'ok' },
          },
        },
        parameters: [
          {
            name: 'id',
            in: 'path',
            required: true,
            schema: {
              type: 'integer',
            },
          },
        ],
      },
    },
  },
  handlers: {
    // your platform specific request handlers here
    getPets: (c, req, res) => res.status(200).json({ result: 'ok' }),
    getPetById: (c, req, res) => res.status(200).json({ result: 'ok' }),
    validationFail: (c, req, res) => res.status(400).json({ err: c.validation.errors }),
    notFound: (c, req, res) => res.status(404).json({ err: 'not found' }),
  },
});

// initalize the backend
api.init();

Express

import express from 'express';

const app = express();
app.use((req, res) => api.handleRequest(req, req, res));
app.listen(9000);

See full Express example

Hapi

import Hapi from 'hapi';

const server = new Hapi.Server({ host: '0.0.0.0', port: 9000 });
server.route({
  method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  path: '/{path*}',
  handler: (req, h) =>
    api.handleRequest(
      {
        method: req.method,
        path: req.path,
        body: req.payload,
        query: req.query,
        headers: req.headers,
      },
      req,
      h,
    ),
});
server.start();

See full Hapi example

AWS Serverless (Lambda)

// API Gateway Proxy handler
module.exports.handler = (event, context) =>
  api.handleRequest(
    {
      method: event.httpMethod,
      path: event.path,
      query: event.queryStringParameters,
      body: event.body,
      headers: event.headers,
    },
    event,
    context,
  );

See full Serverless Lambda example

Azure Function

module.exports = (context, req) =>
  api.handleRequest(
    {
      method: req.method,
      path: req.params.path,
      query: req.query,
      body: req.body,
      headers: req.headers,
    },
    context,
    req,
  );

See full Azure Function example

Registering Handlers for Operations

Handlers are registered for operationIds found in the OpenAPI definitions. You can register handlers as shown above with new OpenAPIBackend() constructor opts, or using the register() and registerHandler() methods.

async function getPetByIdHandler(c, req, res) {
  const { id } = c.request.params;
  const pets = await pets.getPetById(id);
  return res.status(200).json({ result: pets });
}
api.register('getPetById', getPetByIdHandler);

Operation handlers are passed a special Context object as the first argument, which contains the parsed request, the matched API operation and input validation results. The other arguments in the example aboce are Express-specific handler arguments.

Mocking API responses

Mocking APIs with OpenAPI backend is easy. Just register a notImplemented handler and use mockResponseForOperation() to generate mock responses from your OpenAPI spec.

api.registerHandler('notImplemented', (c, req, res) => {
  const mock = api.mockResponseForOperation(c.operation.operationId);
  return res.status(200).json(mock);
});

OpenAPI Backend supports mocking responses using both OpenAPI example objects and JSON Schema.

paths:
  /pets:
    get:
      operationId: getPets
      summary: List pets
      description: Returns all pets in database
      responses:
        '200':
          $ref: '#/components/responses/PetList'
components:
  responses:
    PetList:
      description: List of pets in database
      content:
        'application/json':
          schema:
            type: array
            items:
              type: object
              properties:
                id:
                  type: integer
                  minimum: 1
                name:
                  type: string
                  example: Garfield

This example would produce:

api.mockResponseForOperation('getPets');
// returns: [{ id: 1, name: 'Garfield' }]

See full Mock API example on Express

Contributing

OpenAPI Backend is Free and Open Source Software. Issues and pull requests are more than welcome!

The Chilicorn