Registry / web-framework / openapi-backend

openapi-backend

JSON →
library5.16.1jsnpmunverified

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.

npm install openapi-backend
INSTALL
IMPORT
SIG · OPENAPI-BACKEND
O
openapi-backend
web-frameworkjavascriptv5.16.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OpenAPIBackend
✓ import OpenAPIBackend from 'openapi-backend';
✗ const OpenAPIBackend = require('openapi-backend');
OpenAPIBackend is a default export. The library is primarily designed for ESM environments, especially with its Node.js >=20 requirement; CommonJS `require` is generally not recommended.
Context
✓ import type { Context } from 'openapi-backend';
✗ import { Context } from 'openapi-backend';
The `Context` object, containing request, validation, and security details, is passed to all registered operation handlers. It is a TypeScript type, so `import type` is preferred to avoid runtime import issues.
Request, Response
✓ import type { Request, Response } from 'openapi-backend';
✗ import { Request, Response } from 'openapi-backend';
These are generic TypeScript interfaces for handler arguments, allowing for type-safe interaction while remaining framework-agnostic. They are types, so `import type` is correct.

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'); });
Debug
Known issues
breakingStarting with version 5.x, `openapi-backend` requires Node.js version 20.0.0 or higher. Older Node.js versions are not supported.
fix
Upgrade your Node.js environment to version 20.0.0 or later.
affects: >=5.0.0
gotchaWhen using `openapi-backend` in a TypeScript project, ensure you use `import type` for importing types (e.g., `Context`, `Request`, `Response`) to prevent issues with runtime imports, especially in environments that don't correctly handle type-only imports.
fix
Change `import { TypeName } from 'openapi-backend';` to `import type { TypeName } from 'openapi-backend';` for all type imports.
affects: >=3.0.0
gotchaThe `api.init()` method must be called after registering all handlers and before handling any requests. Failing to call `init()` will prevent the API backend from properly loading your OpenAPI definition and routing requests.
fix
Ensure `api.init()` is invoked once after `api.register()` calls and before any `api.handleRequest()` calls.
affects: >=3.0.0
Errors
Common errors & fixes
TypeError: OpenAPIBackend is not a constructor
Attempting to use `require()` for a library that is primarily ESM-first, or not correctly importing the default export.
fix
Use ESM `import OpenAPIBackend from 'openapi-backend';` instead of CommonJS `const OpenAPIBackend = require('openapi-backend');`.
Error: request validation failed
The incoming API request (parameters, headers, body) does not conform to the schema defined in your OpenAPI Specification.
fix
Inspect `c.validation.errors` within your `validationFail` handler to understand the specific schema violations. Adjust the incoming request or the OpenAPI definition accordingly.
Error: notFound
No `operationId` in your OpenAPI definition matches the incoming request path and method, and a generic `notFound` handler has been triggered.
fix
Verify your OpenAPI definition's `paths` and `operationIds` align with expected API endpoints. Ensure you have registered a handler for the relevant `operationId` or a catch-all `notFound` handler.
Upgrade
Version history
5.16.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources
openapi-backend — npm install openapi-backend · libregistry