How to implement and use Swagger in Node.js in 2021?
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
For the convenience of Syntax;
i) let’s add the babel modules to the project:
npm install @babel/core @babel/node @babel/preset-env
ii) let’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”,
If you don’t have nodemon in your PC, I advise installing it globally.
And then let’s create the src/index.js file and add the following codes:
As you can see, we will reach the posts.js file which includes the APIs, from index.js file with /posts endpoint.
Now let’s create the posts.js file and add to it CRUD operations:
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;
n the last case, the project files should look like this:
Now we have a RESTful web server that runs on the 4001 port. You can run it simply with the npm start command. You can test the CRUD operations with Postman.
Maybe you find it a little complicated that testing APIs with Postman. Here Swagger comes into play.
Adding Swagger to the project
Firstly, let’s install two modules that are necessary for documentation and user interface (UI):
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));
The options variable is an OpenAPI object. It is possible to give some information regarding APIs with this (title, version information, contact information, etc.).
For more information, you can check this link.
And we see that implementation is possible only with one single line code.
It will be more clear when we see the definitions underthe definition field on the display. Note that the server URL and APIs are specified in the options variable.
Now we can display Swagger UI with /api-docs endpoint after we run the server:
And now we can make the specifications that will display and run our APIs that are in the Routes/posts.js file on the Swagger screen. We used the JSON format to define the options variable in the index.js file. But we will use the YAML format for schema definitions. (It is possible to use both formats).
Components Object
I am beginning by defining the Components Object. This object is defined to be used in various parts of the documentation. We can say that is a schema of the data we will use. Unless it won’t be called by any property of documentation, it has no effect on APIs.
/**
* @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
*/
With the Tags feature of Swagger we can create a list of Tags with which we can distinguish which function on Swagger UI belongs to which data. Since we have APIs that belong just to the Posts data, there won’t be confusion about API functions. But in the documentation that includes APIs related to multiple data, Tags are inevitable.
Let’s try to understand the Tag issue better with a screenshot from another RESTful API documentation
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
Post a Comment