Script Valley
REST API Development: Complete Course from Beginner to Production
Production and Best Practices: Logging, Monitoring, Documentation, and DeploymentLesson 6.2

API Documentation with OpenAPI and Swagger

OpenAPI specification, Swagger, swagger-jsdoc, swagger-ui-express, API documentation, JSDoc comments, schema definition, interactive documentation

API Documentation with OpenAPI and Swagger

An undocumented REST API is effectively unusable. OpenAPI (formerly Swagger) is the industry standard specification for documenting REST APIs. It defines your API's endpoints, request and response schemas, authentication methods, and error codes in a machine-readable format that generates interactive documentation automatically.

Setting Up swagger-jsdoc and swagger-ui-express

npm install swagger-jsdoc swagger-ui-express
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'My REST API',
      version: '1.0.0',
      description: 'Complete REST API documentation'
    },
    servers: [{ url: 'http://localhost:3000/api' }],
    components: {
      securitySchemes: {
        bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }
      }
    }
  },
  apis: ['./src/modules/**/*.routes.js']
};

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

Documenting Endpoints with JSDoc

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Get all users
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *     responses:
 *       200:
 *         description: List of users
 *       401:
 *         $ref: '#/components/responses/Unauthorized'
 */

Navigate to http://localhost:3000/api/docs to see an interactive UI where you can read documentation and make live API calls. This is the standard documentation experience developers expect from professional APIs.

Up next

Performance Optimization: Caching, Compression, and Database Indexing

Sign in to track progress