What is exegesis-express?
exegesis-express is an npm package that provides a framework for building APIs using OpenAPI (formerly known as Swagger) specifications. It integrates with Express.js to allow developers to define their API endpoints, request/response validation, and middleware based on OpenAPI definitions.
What are exegesis-express's main functionalities?
API Endpoint Definition
This code demonstrates how to set up an Express server with exegesis-express middleware to handle API endpoints defined in an OpenAPI specification file.
const express = require('express');
const exegesisExpress = require('exegesis-express');
const path = require('path');
async function createServer() {
const app = express();
const options = {
controllers: path.resolve(__dirname, './controllers'),
};
const exegesisMiddleware = await exegesisExpress.middleware(path.resolve(__dirname, './openapi.yaml'), options);
app.use(exegesisMiddleware);
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
return app;
}
createServer().then(app => {
app.listen(3000, () => {
console.log('Listening on port 3000');
});
}).catch(err => {
console.error(err.stack);
process.exit(1);
});
Request/Response Validation
This code sample shows how to enable request and response validation in an Express server using exegesis-express. The `validateResponses` option ensures that responses conform to the OpenAPI specification.
const express = require('express');
const exegesisExpress = require('exegesis-express');
const path = require('path');
async function createServer() {
const app = express();
const options = {
controllers: path.resolve(__dirname, './controllers'),
validateResponses: true, // Enable response validation
};
const exegesisMiddleware = await exegesisExpress.middleware(path.resolve(__dirname, './openapi.yaml'), options);
app.use(exegesisMiddleware);
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
return app;
}
createServer().then(app => {
app.listen(3000, () => {
console.log('Listening on port 3000');
});
}).catch(err => {
console.error(err.stack);
process.exit(1);
});
Custom Middleware Integration
This code demonstrates how to integrate custom middleware into an Express server that uses exegesis-express. The custom middleware logs a message for each request.
const express = require('express');
const exegesisExpress = require('exegesis-express');
const path = require('path');
async function createServer() {
const app = express();
const options = {
controllers: path.resolve(__dirname, './controllers'),
};
const exegesisMiddleware = await exegesisExpress.middleware(path.resolve(__dirname, './openapi.yaml'), options);
app.use(exegesisMiddleware);
// Custom middleware
app.use((req, res, next) => {
console.log('Custom middleware executed');
next();
});
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
return app;
}
createServer().then(app => {
app.listen(3000, () => {
console.log('Listening on port 3000');
});
}).catch(err => {
console.error(err.stack);
process.exit(1);
});
Other packages similar to exegesis-express
swagger-express-middleware
swagger-express-middleware is a package that provides Express middleware for working with Swagger (OpenAPI) documents. It offers features like request validation, mock responses, and more. Compared to exegesis-express, it focuses more on Swagger 2.0 and provides a different set of utilities for handling API requests.
express-openapi-validator
express-openapi-validator is a package that validates API requests and responses against an OpenAPI 3 specification. It integrates with Express.js and provides features like request validation, response validation, and security handling. It is similar to exegesis-express but focuses more on validation and security aspects.
openapi-backend
openapi-backend is a package that helps build and manage backend services using OpenAPI definitions. It provides features like request validation, routing, and response validation. Unlike exegesis-express, it is framework-agnostic and can be used with various server frameworks, not just Express.
exegesis-express
exegesis
n. An explanation or critical interpretation of a text, especially an
API definition document.
-- No dictionary ever
This library implements an Express middleware for
OpenAPI 3.x.
Features
Tutorial
Check out the tutorial here.
Usage
Calling exegesisExpress.middleware(openApiFile, options)
will return a Promise
which resolves to a connect/express middleware (alternatively you can call
exegesisExpress.middleware(openApiFile, options, done)
, if callbacks are your
thing).
openApiFile
is either a path to your openapi.yaml or openapi.json file,
or it can be a JSON object with the contents of your OpenAPI document. This
should have the x-exegesis-controller
extension defined on any paths you want to be able to access.
options
can be anything you can pass to exegesis. At a
minimum, you'll probably want to provide options.controllers
, a path to where
your controller modules
can be found. If you have any security requirements defined, you'll also
want to pass in some authenticators.
To enable response validation, you'll want to provide a validation callback
function via onResponseValidationError()
.
Exegesis's functionality can also be extended using plugins,
which run on every request. Plugins let you add functionality like
role base authorization,
or CORS.
Where to put Exegesis-Express in your middleware stack
Exegesis-express should appear near the top of your middleware stack, before
any body parsers. This is because exegesis will take care of parsing the body
for you, and it can't do that if the body has already been read. If you put
a body parser ahead of exegesis-express, exegesis will try to use req.body
if it's there.
Servers section
OpenAPI 3.x lets you specify what servers your API is available on. For example:
servers:
- url: "/api/v2"
By default, exegesis will take 'servers' into account when routing requests,
so if you have the above servers section, and a path in your API called
"/users", then exegesis will only match the route if the incoming requests has
the URL "/api/v2/users".
If you have path templates in your servers, the variables will be available to
your controllers via context.params.server
.
If you specify the ignoreServers
option, however, exegesis will ignore the
servers section, an route purely based on your paths. This lets you do
something like:
const exegesisMiddleware = await exegesisExpress.middleware(
path.resolve(__dirname, "./openapi.yaml"),
{ ignorePaths: true }
);
app.use("/api/v2", exegesisMiddleware);
which means non-api paths will not even be sent to the exegesis middleware.
Example
import express from "express";
import path from "path";
import http from "http";
import * as exegesisExpress from "exegesis-express";
async function createServer() {
const options = {
controllers: path.resolve(__dirname, "./controllers"),
};
const exegesisMiddleware = await exegesisExpress.middleware(
path.resolve(__dirname, "./openapi.yaml"),
options
);
const app = express();
app.use(exegesisMiddleware);
app.use((req, res) => {
res.status(404).json({ message: `Not found` });
});
app.use((err, req, res, next) => {
res.status(500).json({ message: `Internal error: ${err.message}` });
});
const server = http.createServer(app);
server.listen(3000);
}
Copyright 2018 Jason Walton