Swagger for Node JS API

Sudharsanan Rajaram
2 min readJul 4, 2023

--

Generating a Documentation in Node JS API is quite simple and it has become an essential task for maintaining and scaling up any project. In this tutorial, we will create Swagger documentation for a Node JS API.

Prerequisites

Before we start, we need to make sure we have some prerequisites installed.

  • Node.js installed on your local machine
  • Express.js installed in your project

Installing Swagger Documentation

We need to add the below libraries in the package.json

swagger-jsdoc
swagger-ui-express

Create Swagger Spec

We need to create the Swagger specification for our API. We can create a new file named `swagger.json` or just specifying in the index.js . In this file, we define the API endpoints and other related information.

const swaggerOptions = {
definition: {
openapi: "3.0.0",
info: {
title: "Some Title",
version: "0.1.0",
description:
"Some Description",
contact: {
name: "Project",
url: "https://domain.com/",
email: "someemail@domain.com",
},
},
servers: [
{
url: "http://localhost:3000",
description: "Only for Developers"
},
{
url : "https://dev.com",
description: "Development Server"
},
{
url : "https://stage.com",
description: "Stage Server"
},
{
url : "https://prod.com",
description: "Production Server"
}
],
},
apis: ["./server/routes/*.js", "./server/routes/api/*.js"],
};

Configure Swagger

After creating the Swagger spec, we need to configure Swagger. We can do this by creating a new file named `swagger.js` or embed the same in server.js itself like below

const specs = swaggerJsdoc(swaggerOptions);

Integrate Swagger with the Node JS API

Final step is integrating the spec in express module to serve the documentation

app.use(
"/api-docs",
swaggerUi.serve,
swaggerUi.setup(specs, { explorer: true })
);

After the successful start of the server, the documentation page can be reached in browser from the http://localhost:3000/api-docs

Last and final step is specifying the API’s for documentation. Documentation will be specified through the openapi annotation like below. For more specification on the configuration was prodived in the below link About Swagger Specification | Documentation | Swagger

Sample Router:

/**
* @openapi
* /api/v1/getname:
* get:
* tags: [Widget]
* security:
* - bearerAuth : []
* description: Get the list of Names
* responses:
* 200:
* description: list of Names
* 500:
* description: Some Server Error
* 401:
* description: UnAuthorized Access. Kindly check Bearer Token
*/
router.get('/getname', modulename.exportfunction);

Restart the server and again goto http://localhost:3000/api-docs to the list of api specified.

--

--

Sudharsanan Rajaram

I am a Data Enthusiast ,Programmer, Valuable investor, Good husband