OpenAPI 3.x Express Middleware

4.0.0 · active · verified Wed Apr 22

exegesis-express provides Express middleware for handling OpenAPI 3.x API definitions, acting as a wrapper around the core `exegesis` library. It offers full support for OpenAPI 3.x.x features including request body parsing (JSON, form-urlencoded), response validation, authentication, and extensibility via a plugin system and custom format validation. The current stable version is 4.0.0, released in December 2021. While not on a fixed release cadence, it typically updates in conjunction with its parent `exegesis` library, incorporating bug fixes, security patches, and Node.js version support changes. Key differentiators include comprehensive OpenAPI 3.x conformance, flexible middleware placement, and robust error handling for API-driven applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up an Express server using `exegesis-express` to serve a simple OpenAPI 3.x defined API. It demonstrates how to initialize the middleware with an OpenAPI specification (inline JSON for simplicity), configure controllers, handle response validation errors, and correctly place the middleware within the Express stack.

import express from 'express';
import { middleware } from 'exegesis-express';
import path from 'path';

const openApiDoc = {
  openapi: '3.0.3',
  info: {
    title: 'Example API',
    version: '1.0.0',
  },
  paths: {
    '/greet': {
      get: {
        'x-exegesis-controller': 'GreetingController',
        operationId: 'greetUser',
        parameters: [
          {
            name: 'name',
            in: 'query',
            schema: { type: 'string', default: 'World' },
            required: false,
          },
        ],
        responses: {
          '200': {
            description: 'A greeting message.',
            content: {
              'application/json': {
                schema: { type: 'object', properties: { message: { type: 'string' } } },
              },
            },
          },
        },
      },
    },
  },
};

// Create a simple controller file (e.g., controllers/GreetingController.ts)
// export function greetUser(context) {
//   const name = context.params.query.name || 'World';
//   return { message: `Hello, ${name}!` };
// }

async function createServer() {
  const app = express();

  const exegesisMiddleware = await middleware(openApiDoc, {
    controllers: path.resolve(__dirname, 'controllers'),
    allowMissingControllers: false,
    onResponseValidationError: (error) => {
      console.error('Response validation error:', error);
    },
  });

  // Exegesis-express should be placed before any body parsers if you want
  // it to handle request body parsing itself.
  app.use(exegesisMiddleware);

  // Catch-all for routes not handled by Exegesis (e.g., 404)
  app.use((req, res) => {
    res.status(404).json({ message: 'Not Found' });
  });

  // Global error handler
  app.use((err, req, res, next) => {
    console.error('Unhandled error:', err);
    res.status(500).json({ message: `Internal server error: ${err.message}` });
  });

  app.listen(3000, () => {
    console.log('Server listening on http://localhost:3000');
    console.log('Try: curl http://localhost:3000/greet?name=Alice');
  });
}

createServer().catch(console.error);

view raw JSON →