DEV Community

Swatantra
Swatantra

Posted on • Edited on

How to make a Swagger UI using postman collections in nodejs

Hi Everyone I am Swatantra, I have learned a lot throughout my experience and I want to share a very simple trick to build the swagger UI using the Postman collection without writing much code inside our backend application of nodejs, just be with me I will go step by step in this article.

Step 1

You need to build the basic backend skeleton of your backend project it does not matter whether you have a lot of APIs or not because we only need to focus on the swagger part.

so build the basic skeleton of the backend APIs using nodejs express and whatever dependency you want to use.

Step 2

Install a few extra dependencies for the Swagger UI

npm i postman-to-openapi

npm i swagger-ui-express

npm i yamljs
Enter fullscreen mode Exit fullscreen mode

Step 3

Create one folder inside your project folder named Postman and put your Postman Api collection inside this folder.
and make later on you must provide the exact import path of this folder and the file inside this folder.

Setp 4

Write this code inside your main files like app.js or server.js after you use the app by express.

import postmanToOpenApi from "postman-to-openapi";
import path from "path";
import YAML from "yamljs";
import swaggerUi from "swagger-ui-express";

//swagger Documentation
postmanToOpenApi(
  "postman/Edemy-API.postman_collection.json",
  path.join("postman/swagger.yml"),
  {
    defaultTag: "General",
  }
)
  .then((data) => {
    let result = YAML.load("postman/swagger.yml");
    result.servers[0].url = "/";
    app.use("/swagger", swaggerUi.serve, swaggerUi.setup(result));
  })
  .catch((e) => {
    console.log("Swagger Generation stopped due to some error");
  });
Enter fullscreen mode Exit fullscreen mode

Make sure your Postman collection path is correct otherwise, you will face an error in your application.

Step 4

That's It you just write a small code to build the lots of api documentation in swagger by writing the simple one-liner code.

Now run your program and hit the endpoint localhost: Your_port/swagger
you will get the list of your entire apis in a well-documented format.

If you really like this article please follow me
I am regularly updating my profile and documentation on dev.to 😊

follow on

LinkedIn: https://www.linkedin.com/in/swatantra-goswami/
Github: https://github.com/swatantragoswami09
Youtube: https://www.youtube.com/channel/UCd9Lb7BGkdtu6wIp7KtEJsg

Thanks & signing Off
Swatantra

Top comments (0)