Chapter 9: API Documentation
Chapter 9 of 14
Chapter 9: API Documentation
9.1 OpenAPI/Swagger
OpenAPI (formerly Swagger) provides a standard way to document REST APIs.
// Swagger/OpenAPI setup
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
description: 'API documentation'
},
servers: [
{ url: 'http://localhost:3000', description: 'Development' },
{ url: 'https://api.production.com', description: 'Production' }
]
},
apis: ['./routes/*.js']
};
const swaggerSpec = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
9.2 API Documentation with JSDoc
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* tags: [Users]
* responses:
* 200:
* description: List of users
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/User'
*/
app.get('/api/users', getUsers);
9.3 Interactive Documentation
// Swagger UI provides interactive documentation
// Users can test endpoints directly from the documentation
// Includes request/response examples
// Shows authentication requirements