Why Document APIs?
Good API documentation helps developers understand and use your API effectively. Swagger/OpenAPI provides a standard way to document REST APIs.
Installing Swagger
npm install swagger-jsdoc swagger-ui-express
Setting Up Swagger
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',
},
},
apis: ['./routes/*.js'],
};
const swaggerSpec = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
Documenting Endpoints
/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* tags: [Users]
* responses:
* 200:
* description: List of users
*/
router.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
Benefits
- Interactive API testing
- Auto-generated documentation
- Client SDK generation
- Version control for API changes