{"id":11494,"library":"openapi-backend","title":"OpenAPI Backend","description":"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.","status":"active","version":"5.16.1","language":"javascript","source_language":"en","source_url":"https://github.com/openapistack/openapi-backend","tags":["javascript","openapi","swagger","server","router","validation","mock","express","hapi","typescript"],"install":[{"cmd":"npm install openapi-backend","lang":"bash","label":"npm"},{"cmd":"yarn add openapi-backend","lang":"bash","label":"yarn"},{"cmd":"pnpm add openapi-backend","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const OpenAPIBackend = require('openapi-backend');","symbol":"OpenAPIBackend","correct":"import OpenAPIBackend from 'openapi-backend';"},{"note":"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.","wrong":"import { Context } from 'openapi-backend';","symbol":"Context","correct":"import type { Context } from 'openapi-backend';"},{"note":"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.","wrong":"import { Request, Response } from 'openapi-backend';","symbol":"Request, Response","correct":"import type { Request, Response } from 'openapi-backend';"}],"quickstart":{"code":"import OpenAPIBackend from 'openapi-backend';\nimport express from 'express';\n\n// In a real application, './petstore.yml' would be your OpenAPI definition file.\n// For demonstration, we'll use a minimal inline definition.\nconst api = new OpenAPIBackend({\n  definition: {\n    openapi: '3.0.0',\n    info: { title: 'Petstore API', version: '1.0.0' },\n    paths: {\n      '/pets': {\n        get: {\n          operationId: 'getPets',\n          responses: { 200: { description: 'A list of pets' } },\n        },\n      },\n      '/pets/{petId}': {\n        get: {\n          operationId: 'getPetById',\n          parameters: [\n            { name: 'petId', in: 'path', required: true, schema: { type: 'string' } },\n          ],\n          responses: { 200: { description: 'A single pet' } },\n        },\n      },\n    },\n  },\n});\n\n// register your framework specific request handlers here\napi.register({\n  getPets: (c, req, res) => res.status(200).json({ result: 'all pets' }),\n  getPetById: (c, req, res) => res.status(200).json({ result: `pet with id ${c.request.params.petId}` }),\n  validationFail: (c, req, res) => res.status(400).json({ err: c.validation.errors }),\n  notFound: (c, req, res) => res.status(404).json({ err: 'not found' }),\n});\n\n// initalize the backend\napi.init();\n\nconst app = express();\napp.use(express.json()); // Enable JSON body parsing\n\n// Connect openapi-backend to your Express application\napp.use((req, res) => api.handleRequest(req, req, res));\n\nconst PORT = process.env.PORT ?? 9000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting: http://localhost:9000/pets');\n  console.log('Try visiting: http://localhost:9000/pets/123');\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js environment to version 20.0.0 or later.","message":"Starting with version 5.x, `openapi-backend` requires Node.js version 20.0.0 or higher. Older Node.js versions are not supported.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Change `import { TypeName } from 'openapi-backend';` to `import type { TypeName } from 'openapi-backend';` for all type imports.","message":"When 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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Ensure `api.init()` is invoked once after `api.register()` calls and before any `api.handleRequest()` calls.","message":"The `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.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use ESM `import OpenAPIBackend from 'openapi-backend';` instead of CommonJS `const OpenAPIBackend = require('openapi-backend');`.","cause":"Attempting to use `require()` for a library that is primarily ESM-first, or not correctly importing the default export.","error":"TypeError: OpenAPIBackend is not a constructor"},{"fix":"Inspect `c.validation.errors` within your `validationFail` handler to understand the specific schema violations. Adjust the incoming request or the OpenAPI definition accordingly.","cause":"The incoming API request (parameters, headers, body) does not conform to the schema defined in your OpenAPI Specification.","error":"Error: request validation failed"},{"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.","cause":"No `operationId` in your OpenAPI definition matches the incoming request path and method, and a generic `notFound` handler has been triggered.","error":"Error: notFound"}],"ecosystem":"npm"}