Script Valley
Express.js: APIs and Middleware
Testing and Deploying Express APIsLesson 6.5

How to document an Express API with Swagger/OpenAPI

swagger-jsdoc, swagger-ui-express, OpenAPI 3.0 spec, JSDoc annotations, @swagger tag, path definitions, schema components, /api-docs endpoint, info block

API Documentation with Swagger

Swagger UI generates interactive API documentation from OpenAPI spec annotations written as JSDoc comments in your route files.

npm install swagger-jsdoc swagger-ui-express

Swagger config in app.js

const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const options = {
  definition: {
    openapi: '3.0.0',
    info: { title: 'My API', version: '1.0.0', description: 'Express API docs' },
    components: {
      securitySchemes: {
        bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }
      }
    }
  },
  apis: ['./src/routes/*.js']
};

const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

Annotating a route

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Get all users
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: List of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   id: { type: integer }
 *                   name: { type: string }
 *       401:
 *         description: Unauthorized
 */
router.get('/users', authenticate, getUsers);

Visit /api-docs in your browser to see the interactive UI. The UI lets you make real API calls directly from the docs.