Implementing API Documentation

1. Installing swagger-ui-express

Example: Install

npm i swagger-ui-express swagger-jsdoc

2. Creating OpenAPI Specification

Example: openapi.yaml (3.1)

openapi: 3.1.0
info:
  title: Example API
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: List users
      responses:
        "200": { description: OK }

3. Defining API Endpoints

Example: Endpoint definition

paths:
  /users/{id}:
    get:
      operationId: getUser
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        "200":
          description: User
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404": { description: Not found }

4. Documenting Request Parameters

inWhere
pathURL path placeholder
query?key=value
headerCustom HTTP header
cookieCookie value

5. Documenting Response Schemas

Example: Schema component

components:
  schemas:
    User:
      type: object
      required: [id, email]
      properties:
        id:    { type: integer, example: 42 }
        email: { type: string, format: email }
        role:  { type: string, enum: [admin, user] }

6. Setting Up Swagger UI

Example: Mount UI

import swaggerUi from "swagger-ui-express";
import openapi from "./openapi.json" with { type: "json" };
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openapi));

7. Using swagger-jsdoc for Annotations

Example: JSDoc annotations

import swaggerJSDoc from "swagger-jsdoc";

/**
 * @openapi
 * /users:
 *   get:
 *     summary: List users
 *     responses:
 *       200: { description: OK }
 */
app.get("/users", listUsers);

const spec = swaggerJSDoc({
  definition: { openapi: "3.1.0", info: { title: "API", version: "1.0.0" } },
  apis: ["./src/routes/*.js"]
});

8. Documenting Authentication

Example: securitySchemes

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

9. Generating Documentation from Routes

Example: zod-openapi

import { OpenApiGeneratorV31, OpenAPIRegistry } from "@asteasolutions/zod-to-openapi";
const registry = new OpenAPIRegistry();
registry.registerPath({ method: "get", path: "/users", responses: { 200: { description: "OK" } } });
const spec = new OpenApiGeneratorV31(registry.definitions).generateDocument({
  openapi: "3.1.0", info: { title: "API", version: "1.0.0" }
});

10. Versioning API Documentation

Example: Mount per-version

app.use("/api-docs/v1", swaggerUi.serveFiles(specV1, {}), swaggerUi.setup(specV1));
app.use("/api-docs/v2", swaggerUi.serveFiles(specV2, {}), swaggerUi.setup(specV2));