Swagger is a powerful tool for designing, building, and documenting APIs. It provides a way to describe the structure of your RESTful APIs so that both humans and computers can understand them. In an Express.js application, you can use the swagger-jsdoc
and swagger-ui-express
libraries to generate and display Swagger documentation. Here's a step-by-step guide:
Install Dependencies: First, install the required npm packages:
bashnpm install swagger-jsdoc swagger-ui-express --save
Setup Swagger Options:
Create a new file, for example, swaggerOptions.js
, to define the Swagger options:
javascriptconst swaggerJsdoc = require('swagger-jsdoc');
const options = {
swaggerDefinition: {
openapi: '3.0.0',
info: {
title: 'Express API with Swagger',
version: '1.0.0',
description: 'Documentation for Express API with Swagger',
},
},
apis: ['./routes/*.js'], // Add your API routes file(s)
};
const specs = swaggerJsdoc(options);
module.exports = specs;
Integrate Swagger UI in Express App:
In your main Express application file (e.g., app.js
), integrate Swagger UI:
javascriptconst express = require('express');
const swaggerUi = require('swagger-ui-express');
const specs = require('./swaggerOptions'); // Import the Swagger options file
const app = express();
// ... Your existing Express setup ...
// Serve Swagger UI at /api-docs endpoint
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
// ... Your routes and other middleware ...
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Document Your API Routes: In your Express route files, add Swagger annotations using JSDoc comments. Here's an example:
javascript/**
* @swagger
* /api/users:
* get:
* summary: Get all users
* description: Returns a list of all users
* responses:
* 200:
* description: Successful response
* 500:
* description: Internal server error
*/
router.get('/api/users', (req, res) => {
// Your route logic here
});
Generate and View Swagger Documentation:
Run your Express app and navigate to http://localhost:3000/api-docs
in your web browser. You should see the Swagger UI, which provides interactive documentation for your API.
That's it! You've now integrated Swagger documentation into your Express.js application. Remember to update the Swagger annotations in your route files as your API evolves.