OpenAPI Backend

5.16.1 · active · verified Sun Apr 19

openapi-backend is a robust and framework-agnostic middleware library for Node.js, designed to streamline API development by leveraging OpenAPI Specification definitions. It provides capabilities for request validation, routing based on operationIds, authentication via security schemes, and automatic response mocking from examples or schemas. The current stable version is 5.16.1, with an active release cadence reflecting continuous development and maintenance. Key differentiators include its agnosticism towards specific web frameworks (e.g., Express, Hapi, Koa, Serverless Lambda), its use of AJV for highly performant JSON Schema validation, and its TypeScript-first design which includes comprehensive type definitions. It operates without generating any code, offering a clean and efficient runtime, and supports OpenAPI 3.1. This library simplifies API implementation by consolidating common backend concerns into a single, declarative tool, minimizing boilerplate code and ensuring adherence to API contracts.

Common errors

Warnings

Install

Imports

Quickstart

This code snippet demonstrates the fundamental steps to initialize `openapi-backend` from an OpenAPI definition (here, a minimal inline one), register custom handlers for specific API operations (like `getPets` and `getPetById`), and implement generic handlers for validation failures and unmatched routes. It then integrates this setup with an Express application, showing how to connect the library's routing and validation logic to custom application logic, providing a basic functional API.

import OpenAPIBackend from 'openapi-backend';
import express from 'express';

// In a real application, './petstore.yml' would be your OpenAPI definition file.
// For demonstration, we'll use a minimal inline definition.
const api = new OpenAPIBackend({
  definition: {
    openapi: '3.0.0',
    info: { title: 'Petstore API', version: '1.0.0' },
    paths: {
      '/pets': {
        get: {
          operationId: 'getPets',
          responses: { 200: { description: 'A list of pets' } },
        },
      },
      '/pets/{petId}': {
        get: {
          operationId: 'getPetById',
          parameters: [
            { name: 'petId', in: 'path', required: true, schema: { type: 'string' } },
          ],
          responses: { 200: { description: 'A single pet' } },
        },
      },
    },
  },
});

// register your framework specific request handlers here
api.register({
  getPets: (c, req, res) => res.status(200).json({ result: 'all pets' }),
  getPetById: (c, req, res) => res.status(200).json({ result: `pet with id ${c.request.params.petId}` }),
  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();

const app = express();
app.use(express.json()); // Enable JSON body parsing

// Connect openapi-backend to your Express application
app.use((req, res) => api.handleRequest(req, req, res));

const PORT = process.env.PORT ?? 9000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try visiting: http://localhost:9000/pets');
  console.log('Try visiting: http://localhost:9000/pets/123');
});

view raw JSON →