Node.js

How To Integrate Swagger With A NodeJS REST API

We’ll learn how to add swagger to Node and Express.js in this blog. API development has become a necessary component of any web project. APIs are used to separate the server and the client. The consumption of JSON responses on the UI side has grown more widespread since the introduction of REST APIs.

This post will look at an example project that shows how to use Swagger with the Nodejs REST API.

Prerequisites:

Before you begin this project, you should know a few things. To execute nodejs on your PC, you should first install it. For the development environment, you must be familiar with nodemon.

  1. NodeJs
  2. Nodemon
  3. Swagger
npm install nodemon
npm install swagger-jsdoc swagger-ui-express

Output:

This is a small nodejs API sample example with four API requests. This is a basic to-do software that allows you to create, edit, delete and update items. Here’s the entire example, complete with swagger documentation.

Let’s Start Implementation,

Let’s look at how to add swagger documentation to the Nodejs REST API. Consider the Rest API below, which includes four HTTP operations: post, get, delete, and put.

const express = require('express');
const path = require('path');
const app = express(),
    bodyParser = require('body-parser'),
    fs = require('fs'),
    port = 3000;

let datas = [
    {
        id: 1,
        task: 'data1',
        assignee: 'umang',
        status: 'completed'
    },
    {
        id: 2,
        task: 'data2',
        assignee: 'shahjaha',
        status: 'completed'
    },
    {
        id: 3,
        task: 'data3',
        assignee: 'ankit',
        status: 'completed'
    },
    {
        id: 4,
        task: 'data4',
        assignee: 'vikas',
        status: 'completed'
    },
];

app.use(bodyParser.json());

app.get('/api/todos', (req, res) => {
    res.json(datas);
});

app.post('/api/addtodo', (req, res) => {
    const data = req.body.task;
    datas.push(data);
    res.json(datas); 
});

app.delete('/api/deletetodo/:id', (req, res) => {
    datas = datas.filter(t => t.id != req.params.id);
    res.json(datas);
});

app.put('/api/updateotodo', (req, res) => {
    let taskToUpdate = req.body.task;
    datas = datas.map(x => {
        if(x.id == taskToUpdate.id) x = taskToUpdate;
        return x;
    });
    res.json(datas);
});

app.get('/', (req,res) => {
    res.send(`<h1>API Sucessfully host on this port: ${port}</h1>`);
});

app.listen(port, () => {
    console.log(`port--->${port}`);
});

The first step is to run the following command to install swagger-related dependencies.

npm install swagger-ui-express swagger-jsdoc

Before you add swagger documents to your REST API, there are two things you should know.

Swagger.json

The first step is to add the swagger.json file, which will define the operations. You can specify schemas for request and response objects, as well as parameters, body, and descriptions for each HTTP action, among other things.

{
    "swagger": "2.0",
    "info": {
        "description": "This is the swagger node.js API project",
        "version": "1.0.0",
        "title": "Swagger API Node.Js",
        "contect": {
            "email": "test@mail.com",
            "mobile-no": "+111111111"
        },
        "license": {
            "name": "Apeche 2.0",
            "url": "#"
        }
    },
    "schemas": [
        "http"
    ],
    "host": "localhost:3000",
    "basePath": "/api",
    "paths": {
        "/api/todos": {
            "get": {
                "summary": "Get all the tasks",
                "description": "Get all the tasks",
                "produces": [
                    "application/json"
                ],
                "parameters": [],
                "responses": {
                    "200": {
                        "description": "successful operation",
                        "sechema": {
                            "type": "array",
                            "item": {
                                "$ref": "#/definitions/todoResponse"
                            }
                        }
                    },
                    "400": {
                        "description": "Invalid Status value",
                        "sechema": {
                            "$ref": "#/definitions/InvalidResponse"
                        }
                    }
                }
            }
        },
        "/api/addtodo" : {
            "post" : {
                "summary" : "Save the task",
                "description": "Save the task",
                "produces": ["application/json"],
                "consumes": ["application/json"],
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "task object",
                        "required": true,
                        "schema": {
                            "type": "object",
                            "properties": {
                                "task" : {
                                    "type": "object",
                                    "$ref": "#/definitions/Task"
                                } 
                            }
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "successful operation",
                        "schema": {
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/todoResponse"
                            }
                        }
                    },
                    "400": {
                        "description": "Invalid status value",
                        "schema": {
                            "$ref": "#/definitions/InvalidResponse"
                        }
                    }
                }
            }
        },
        "/api/updateotodo" : {
            "put" : {
                "summary" : "Update the tasks",
                "description": "Update the tasks",
                "produces": ["application/json"],
                "parameters": [
                    {
                        "in": "body",
                        "name": "body",
                        "description": "task object",
                        "required": true,
                        "schema": {
                            "type": "object",
                            "properties": {
                                "task" : {
                                    "type": "object",
                                    "$ref": "#/definitions/Task"
                                } 
                            }
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "successful operation",
                        "schema": {
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/todoResponse"
                            }
                        }
                    },
                    "400": {
                        "description": "Invalid status value",
                        "schema": {
                            "$ref": "#/definitions/InvalidResponse"
                        }
                    }
                }
            }
        },
        "/api/deletetodo/{id}" : {
            "delete" : {
                "summary" : "Delete the task",
                "description": "Delete the task",
                "produces": ["application/json"],
                "parameters": [
                    {
                        "name": "id",
                        "in": "path",
                        "description": "task id that needs to be deleted",
                        "required": true,
                        "type": "string"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "successful operation",
                        "schema": {
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/todoResponse"
                            }
                        }
                    },
                    "400": {
                        "description": "Invalid status value",
                        "schema": {
                            "$ref": "#/definitions/InvalidResponse"
                        }
                    }
                }
            }
        }
    },
    "definitions": {
        "todoResponse": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "integer"
                },
                "task": {
                    "type": "string"
                },
                "assign": {
                    "type": "string"
                },
                "status": {
                    "type": "string"
                }
            }
        },
        "Task": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "integer"
                },
                "task": {
                    "type": "string"
                },
                "assignee": {
                    "type": "string"
                },
                "status": {
                    "type": "string"
                }
            }
        },
        "InvalidResponse": {
            "type": "object",
            "properties": {
                "statusCode": {
                    "type": "string"
                },
                "message": {
                    "type": "string"
                }
            }
        }
    }
}

The schemas are also visible on the swagger page of the Nodejs Rest API.

Once you’ve got the swagger.json files in place, you’ll need to add the swagger-related code to server.js.

// import library and files

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

// let express to use this (Add after body-parser)
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Here is the complete app.js file

const express = require('express');
const path = require('path');
const app = express(),
    bodyParser = require('body-parser'),
    fs = require('fs'),
    port = 3000;

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

let datas = [
    {
        id: 1,
        task: 'data1',
        assignee: 'umang',
        status: 'completed'
    },
    {
        id: 2,
        task: 'data2',
        assignee: 'shahjaha',
        status: 'completed'
    },
    {
        id: 3,
        task: 'data3',
        assignee: 'ankit',
        status: 'completed'
    },
    {
        id: 4,
        task: 'data4',
        assignee: 'vikas',
        status: 'completed'
    },
];

app.use(bodyParser.json());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));


app.get('/api/todos', (req, res) => {
    res.json(datas);
});

app.post('/api/addtodo', (req, res) => {
    const data = req.body.task;
    datas.push(data);
    res.json(datas); 
});

app.delete('/api/deletetodo/:id', (req, res) => {
    datas = datas.filter(t => t.id != req.params.id);
    res.json(datas);
});

app.put('/api/updateotodo', (req, res) => {
    let taskToUpdate = req.body.task;
    datas = datas.map(x => {
        if(x.id == taskToUpdate.id) x = taskToUpdate;
        return x;
    });
    res.json(datas);
});

app.get('/', (req,res) => {
    res.send(`<h1>API Sucessfully host on this port: ${port}</h1>`);
});

app.listen(port, () => {
    console.log(`port--->${port}`);
});

You can start the project with the following command.

npm run

Here’s the whole example, which shows how to use the swagger docs to make all of the calls. http://localhost:3000/api-docs/ leads to the swagger page. The complete documentation may be found here.

That’s it.

I hope you guys understand how I can do this. Let me know if you face any difficulties.

You can watch my previous blog here.

Happy Coding {;}

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago