Testing, Documentation, and Production DeploymentLesson 6.2
OpenAPI documentation — generating docs from your Express API
OpenAPI 3.0, swagger-ui-express, swagger-jsdoc, JSDoc annotations, paths and schemas, request body definition, response schemas, live documentation UI
API Documentation with OpenAPI and Swagger UI
OpenAPI (formerly Swagger) is the industry standard for REST API documentation. It produces an interactive UI where developers can read specs and test endpoints in-browser.
Setup
npm install swagger-ui-express swagger-jsdoc// config/swagger.js
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: { title: 'My API', version: '1.0.0' },
components: {
securitySchemes: {
bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }
}
}
},
apis: ['./routes/*.js'] // files with JSDoc annotations
};
module.exports = swaggerJsdoc(options);Annotating Routes
/**
* @openapi
* /users/{id}:
* get:
* summary: Get a user by ID
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: User object
* 404:
* description: User not found
*/
router.get('/:id', authenticate, getUser);// Mount Swagger UI
const swaggerUi = require('swagger-ui-express');
const specs = require('./config/swagger');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));