Steps to Configure Swagger with Node.js:
How to Configure Swagger with Node.js
Steps to Configure Swagger with Node.js:
1. Install Required Packages
You’ll need two main packages:
swagger-jsdoc
: To generate Swagger specification (OpenAPI) from your code.
swagger-ui-express
: To serve the Swagger UI on an endpoint.
npm install swagger-jsdoc swagger-ui-express
2. Create a Swagger Configuration File
In your project directory, create a new file named swaggerConfig.js
to define the Swagger documentation settings.
Example content for swaggerConfig.js
:
const swaggerJSDoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Your API Title',
version: '1.0.0',
description: 'API Documentation for your Node.js app',
},
},
apis: ['./routes/*.js'], // Path to your route files
};
const swaggerSpec = swaggerJSDoc(options);
module.exports = swaggerSpec;
3. Set Up Swagger in Your Express App
In your app.js
or server.js
file (the main entry point of your Node.js app), add the following code to serve the Swagger documentation on a specific route (e.g., /api-docs
):
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swaggerConfig');
const app = express();
// Swagger setup
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Example: Other routes
app.get('/api/v1/example', (req, res) => {
res.send('This is an example API route');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
4. Add Swagger Comments in Your Routes
In your route files (e.g., routes/example.js
), add comments that Swagger can use to generate the API documentation. Here's an example of how to do that:
/**
* @swagger
* /api/v1/example:
* get:
* summary: Example endpoint
* responses:
* 200:
* description: Successful response
*/
app.get('/api/v1/example', (req, res) => {
res.send('This is an example API route');
});
5. Access the Swagger UI
Once you've set everything up, you can run your application:
node app.js
Then, navigate to http://localhost:3000/api-docs
in your browser. You'll see the Swagger UI where you can explore and test your API.
This format includes headings, code blocks, and clear steps, making it easily readable and usable within Notion. You can copy-paste it directly into a Notion page for clean documentation!