import express from 'express'; import swaggerJSDoc from 'swagger-jsdoc'; const app = express(); const options = { definition: { openapi: '3.0.0', info: { title: 'Sample API', version: '1.0.0' } }, apis: ['./routes/*.js'] }; const swaggerSpec = swaggerJSDoc(options); app.get('/api-docs.json', (req, res) => { res.json(swaggerSpec); }); app.listen(3000);
The swaggerJSDoc function reads the options and extracts API documentation from the specified files. It returns a JSON object following the OpenAPI format. The endpoint /api-docs.json sends this JSON as response.
The swagger-jsdoc options require a definition key containing the OpenAPI version and info. Options A, C, and D miss this structure or info.
const options = {
definition: {
openapi: '3.0.0',
info: { title: 'API', version: '1.0' }
},
apis: ['./src/routes/*.js']
};
const swaggerSpec = swaggerJSDoc(options);swagger-jsdoc reads the files listed in 'apis' and looks for JSDoc comments with Swagger annotations to build the 'paths' object. If these comments are missing, 'paths' will be empty.
const spec1 = swaggerJSDoc({ definition: { openapi: '3.0.0', info: { title: 'API1' } }, apis: ['./routes1/*.js'] });
const spec2 = swaggerJSDoc({ definition: { openapi: '3.0.0', info: { title: 'API2' } }, apis: ['./routes2/*.js'] });
const merged = { ...spec1, paths: { ...spec1.paths, ...spec2.paths } };swaggerJSDoc returns a JSON object. Calling it multiple times returns separate specs. Merging paths manually combines endpoints, but other fields like 'info' remain from the first spec unless merged explicitly.
The 'apis' option is an array of file paths or glob patterns. swagger-jsdoc scans these files for JSDoc comments containing Swagger annotations to build the API documentation JSON.