API Documentation with Swagger/OpenAPI
Good API documentation is as important as good code. The OpenAPI Specification (OAS 3.0), formerly Swagger, is the industry standard for describing REST APIs. It auto-generates interactive documentation and enables client SDK generation.
1 OpenAPI 3.0 Spec Structure
YAML — openapi.yaml
openapi: 3.0.3
info:
title: Products REST API
description: A complete product management REST API
version: 1.0.0
contact:
name: API Support
email: api@example.com
servers:
- url: https://api.example.com/api/v1
description: Production
- url: http://localhost:3000/api/v1
description: Development
paths:
/products:
get:
summary: List all products
tags: [Products]
parameters:
- name: category
in: query
schema: { type: string }
- name: page
in: query
schema: { type: integer, default: 1 }
- name: limit
in: query
schema: { type: integer, default: 20, maximum: 100 }
responses:
"200":
description: Successful response
content:
application/json:
schema:
type: object
properties:
success: { type: boolean }
data:
type: array
items: { $ref: "#/components/schemas/Product" }
components:
schemas:
Product:
type: object
required: [name, price, category]
properties:
id: { type: integer, example: 1 }
name: { type: string, example: "Mechanical Keyboard" }
price: { type: integer, example: 8999 }
category: { type: string, example: "electronics" }
inStock: { type: boolean, example: true }
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
2 Serving Swagger UI in Express
JavaScript — Swagger UI Setup
npm install swagger-ui-express swagger-jsdoc
const swaggerUi = require("swagger-ui-express");
const swaggerJsdoc = require("swagger-jsdoc");
const options = {
definition: {
openapi: "3.0.3",
info: { title: "My REST API", version: "1.0.0" }
},
apis: ["./src/routes/*.js"] // parses JSDoc annotations
};
const spec = swaggerJsdoc(options);
app.use("/api/docs", swaggerUi.serve, swaggerUi.setup(spec));
// Visit http://localhost:3000/api/docs
4 Code Challenge
Challenge: Add JSDoc
@swagger annotations to your GET /products and POST /products routes. Document all query parameters, request body schema, and possible response codes. Verify the Swagger UI renders it correctly.