Express OpenAPI Framework

12.1.3 · active · verified Sun Apr 19

express-openapi is an unopinionated framework designed to integrate OpenAPI (formerly Swagger) specifications into Express.js applications. It currently supports OpenAPI versions 2.0 and 3.0. The library prioritizes performance and extensive testing, aiming to keep development as close to native Express patterns as possible while providing robust API documentation and validation capabilities. It achieves its features, such as parameter defaults, type coercion, request/response validation, and security handling, by leveraging a suite of modular `openapi-*` packages. The current stable version is 12.1.3. While not explicitly stating a release cadence, its version history suggests active development. Key differentiators include its flexible, unobtrusive design, comprehensive middleware configuration via vendor extensions, and the ability to maintain API documentation in sync with application code.

Common errors

Warnings

Install

Imports

Quickstart

Sets up an Express server, initializes `express-openapi` with an in-memory OpenAPI 3.0 specification, defines a simple '/hello' endpoint, and serves Swagger UI for API exploration. This demonstrates basic setup, routing, and documentation generation.

import express from 'express';
import { initialize } from 'express-openapi';
import * as swaggerUi from 'swagger-ui-express';

const app = express();
const PORT = process.env.PORT ?? 3000;

// Basic API Document - OpenAPI 3.0
const apiDoc = {
  openapi: '3.0.0',
  info: {
    title: 'My Simple API',
    version: '1.0.0',
    description: 'A simple API with Express and OpenAPI'
  },
  paths: {
    '/hello': {
      get: {
        summary: 'Responds with a greeting',
        responses: {
          '200': {
            description: 'Successful response',
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    message: { type: 'string' }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
};

// Create a dummy 'operations' object for the path handler
const operations = {
  get: (req: express.Request, res: express.Response) => {
    res.status(200).json({ message: 'Hello, OpenAPI!' });
  }
};

initialize({
  app,
  apiDoc,
  paths: [
    {
      path: '/hello',
      module: operations
    }
  ],
  docsPath: '/api-docs' // Path where Swagger UI will be served
});

// Serve Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(apiDoc as swaggerUi.JsonObject));

// Start the Express server
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
  console.log(`API endpoint at http://localhost:${PORT}/hello`);
});

view raw JSON →