How to implement and use Swagger in Node.js in 2021?

In this blog article, we will go discuss on the topic of "How to implement and use Swagger in Nodejs for 2021 Web Developers". I hope by reading this article will help you to understand the usage of Swagger for managing and documenting the RestAPI.

Let's get started !!!

 

About Swagger :


Swagger is a set of open-source software tools built around the OpenAPI Specification with which we can build, document, and test our APIs.

You can get more data about Swagger from its site.

In this article, I will discuss;

the most effective method to actualize Swagger to a RESTful web worker worked with Node.js

Strut UI

Programming interface documentation

I will proceed to tell accepting that you know about Node.js and RESTful API ideas at any rate at a fundamental level and I will utilize VS Code as the code proofreader.

Right off the bat we should make a RESTful web worker:

I explore the cursor to the document I will make the venture in the terminal and I am making the package.json record with the accompanying order:

npm init --y

Since I will not utilize an information base in the venture, we should make counterfeit information. For that, I am making a document called data.js and adding a cluster that comprises of some information in JSON design. The situation of the phony information is that a few creators and their posts.
const data = [
{
userId: 1,
id: 1,
title:
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body:
"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
},
{
userId: 1,
id: 2,
title: "qui est esse",
body:
"est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
},
{
userId: 1,
id: 3,
title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
body:
"et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut",
},
];
module.exports = data;

Now let’s add the packages that are necessary to create the server:

npm install express cors morgan body-parser dotenv


npm install @babel/core @babel/node @babel/preset-env


iilet’s create the .babelrc file and add the following code:
{
“presets”: [“@babel/preset-env”]
}

And finally, let’s add the following code to scripts field in the package.json file

“start”: “nodemon — exec babel-node src/index.js”,





import express from "express";
import cors from "cors";
import morgan from "morgan";
import dotenv from "dotenv";
import postRouter from "../Routes/posts";

const PORT = process.env.PORT || 4001;
dotenv.config();

const app = express();

app.use(morgan("dev"));
app.use(cors());


app.use("/posts", postRouter);

app.listen(PORT, () => console.log(`Server runs on port ${PORT}`));






import express from "express";
import data from "../data";
import bodyParser from "body-parser";
const postRouter = express.Router();
postRouter.use(bodyParser.json()); // to use body object in requests

postRouter.get("/", (req, res) => {
res.send(data);
});

postRouter.get("/:id", (req, res) => {
const post = data.find((post) => post.id === +req.params.id);
if (!post) {
res.sendStatus(404);
}
res.send(post);
});

postRouter.post("/", (req, res) => {
try {
const post = {
...req.body,
id: data.length + 1,
};
data.push(post);
res.send(post);
} catch (error) {
return res.status(500).send(error);
}
});

postRouter.put("/:id", (req, res) => {
try {
let post = data.find((post) => post.id === +req.params.id);
post.userId = req.body.userId;
post.title = req.body.title;
post.body = req.body.body;

res.send(post);
} catch (error) {
return res.status(500).send(error);
}
});

postRouter.delete("/:id", (req, res) => {
let post = data.find((post) => post.id === +req.params.id);
const index = data.indexOf(post);

if (post) {
data.splice(index, 1);
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});

module.exports = postRouter;








Image for post







Adding Swagger to the project



npm install swagger-jsdoc swagger-ui-express


And I am importing these two modules in the index.js file:
import swaggerUI from “swagger-ui-express”;
import swaggerJsDoc from “swagger-jsdoc”;

And now, in index.js let’s make some necessary definitions for documentation of APIs and implementation of Swagger UI:
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "Library API",
version: "1.0.0",
description: "A simple Express Library API",
termsOfService: "http://example.com/terms/",
contact: {
name: "API Support",
url: "http://www.exmaple.com/support",
email: "support@example.com",
},
},

servers: [
{
url: "http://localhost:4001",
description: "My API Documentation",
},
],
},
apis: ["./Routes/*.js"],
};

const specs = swaggerJsDoc(options);
app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(specs));













 







Components Object




/**
* @swagger
* components:
* schemas:
* Post:
* type: object
* required:
* - userId
* - title
* - body
* properties:
* id:
* type: integer
* description: The Auto-generated id of a post
* userId:
* type: integer
* description: id of author
* title:
* type: string
* description: title of post
* body:
* type: string
* descripton: content of post *
* example:
* id: 1
* userId: 1
* title: my title
* body: my article
*
*/

For more information about how to add more properties to Components Object, you can check this link.

Tags


/**
* @swagger
* tags:
* name: Posts
* description: posts of users
*/










Image for post






Also read :How to create a blog in PHP and MySQL database in 2020?

How to Fetch Data in React with Example in 2021 ?

 

Comments

Popular posts from this blog

How to optimizations by Angular in 2021?

How to create a blog in PHP and MySQL database - DB design

Secure React SPA using Keycloak with OpenID Connect in 2021