To use express-openapi, follow these four steps to set up a documented API with automatic path generation and dependency injection:
- Create an
apiDoc: Define your main OpenAPI specification (Swagger 2.0 or OpenAPI 3.0) in a JavaScript object or a YAML file. You can leave the paths object empty, as express-openapi will populate it based on your path handlers. - Create path handlers: Place your path handlers in a directory (e.g.,
./api-v1/paths/). Each file should export an object where keys are HTTP methods (e.g., GET, POST). To enable OpenAPI features like validation for a specific method, attach an apiDoc property to that method function. - Create services: Define your business logic in service files. These can be injected into your path handlers.
- Initialize the app: Use the
initialize function, passing your Express app, the apiDoc, the directory containing your paths, and a dependencies object to map service names to their implementations.
express-openapi automatically adds a Swagger UI route at apiDoc.basePath + args.docsPath.
// 1. api-doc.js
const apiDoc = {
swagger: '2.0',
basePath: '/v1',
info: { title: 'API', version: '1.0.0' },
definitions: { ... },
paths: {}
};
// 2. paths/worlds.js
export default function(worldsService) {
let operations = { GET };
function GET(req, res, next) {
res.status(200).json(worldsService.getWorlds(req.query.worldName));
}
GET.apiDoc = {
summary: 'Returns worlds by name.',
parameters: [{ in: 'query', name: 'worldName', required: true, type: 'string' }],
responses: { 200: { description: 'Success', schema: { type: 'array', items: { $ref: '#/definitions/World' } } } }
};
return operations;
}
// 3. services/worldsService.js
const worldsService = { getWorlds: (name) => [...] };
// 4. app.js
import { initialize } from 'express-openapi';
const app = express();
initialize({
app,
apiDoc: v1ApiDoc,
dependencies: { worldsService: v1WorldsService },
paths: './api-v1/paths'
});
app.listen(3000);