How To Add Swagger To NodeJS REST API

Ankit Kumar Rajpoot
4 min readJan 26, 2023

This article will discuss how to set up Swagger API documentation with NodeJs and ExpressJs projects.

You have to follow these steps:-

Step 1:- First you need to install two dev dependencies these are given below:

a. swagger-autogen

b. swagger-ui-express

Step 2:- Create one folder inside your root directory, which name will be doc because my setup is based on doc folder but you can use any name base on your requirement.

Project structure

Step 3:- Next you have to create a swagger.js file inside the doc folder that’s context will be like this.

/* Swagger configuration */
const options = {
openapi: 'OpenAPI 3', // Enable/Disable OpenAPI. By default is null
language: 'en-US', // Change response language. By default is 'en-US'
disableLogs: false, // Enable/Disable logs. By default is false
autoHeaders: false, // Enable/Disable automatic headers capture. By default is true
autoQuery: false, // Enable/Disable automatic query capture. By default is true
autoBody: false // Enable/Disable automatic body capture. By default is true
}

const config = require('../config/cloud');
const swaggerAutogen = require('swagger-autogen')();
const msg = require('../utils/lang/messages');

const doc = {
info: {
version: '2.0.0', // by default: '1.0.0'
title: 'CloudAgent Apis', // by default: 'REST API'
description: 'API for Managing queue calls', // by default: ''
contact: {
'name': 'API Support',
'email': 'rajputankit22@gmail.com'
},
},
host: config.swagger.host, // by default: 'localhost:3000'
basePath: '/', // by default: '/'
schemes: ['http'], // by default: ['http']
consumes: ['application/json'], // by default: ['application/json']
produces: ['application/json'], // by default: ['application/json']
tags: [ // by default: empty Array
{
name: 'Queue CRUD', // Tag name
description: 'Queue related apis', // Tag description
},
{
name: 'Health',
description: 'Health Check'
}
],
securityDefinitions: {}, // by default: empty object
definitions: {
helathResponse: {
code: msg.response.CAG001.code,
message: msg.response.CAG001.message,
},
'errorResponse.400': {
code: msg.response.CAGE002.code,
message: msg.response.CAGE002.message,
},
'errorResponse.403': {
code: msg.response.CAGE001.code,
message: msg.response.CAGE001.message,
},
'errorResponse.404': {
"code": "404",
"message": "Not found",
},
'errorResponse.500': {
code: msg.response.CAGE003.code,
message: msg.response.CAGE003.message,
}
}, // by default: empty object (Swagger 2.0)
};

const outputFile = './docs/swagger.json';
const endpointsFiles = ['./app.js', './controllers/*.js'];

/* NOTE: if you use the express Router, you must pass in the
'endpointsFiles' only the root file where the route starts,
such as: index.js, app.js, routes.js, ... */
swaggerAutogen(outputFile, endpointsFiles, doc);

// swaggerAutogen(outputFile, endpointsFiles, doc).then(() => {
// require('./index.js'); // Your project's root file
// });

Step 4:- We have to set up the script to run the swagger-autogen inside the package.json file.

"swagger-autogen": "node ./docs/swagger.js",  // Add this line inside the scripts object

Step 5:- Now we will generate the swagger.json file via the given command.

$ npm run swagger-autogen

Now the setup is ready but we don't have any API document, we will write the document for a sample health API.

this is the sample for the health controller

//api for health checkup
exports.health = async (req, res) => {
/*
#swagger.tags = ['Health']
#swagger.summary = 'This is the health API.'
#swagger.description = 'This API response tells us service is up or down.'
#swagger.consumes = ['application/json']
#swagger.produces = ['application/json']
#swagger.responses[200] = {
description: 'Service is',
schema: { $ref: '#/definitions/helathResponse' }
}
#swagger.responses[500] = {
description: 'Server Issue',
schema: { $ref: '#/definitions/errorResponse.500' }
}
#swagger.responses[404] = {
description: 'Not found',
schema: { $ref: '#/definitions/errorResponse.404' }
}
*/
res.send({
code: msg.response.CAG001.code,
message: msg.response.CAG001.message,
});
}

now we will run again the autogen command for regenerate the swagger.json file.

Step 7:- Now we have to open a route for the swagger UI, you can add this content in your app.js file.

 const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./docs/swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

run your app and hit the HTTP:localhost:3001/api-docs/

you can see this page in your browser

That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!

--

--

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.