Add Swagger OpenAPI in Node.js and Express

Add Swagger OpenAPI in Nodejs and Express

Today in this article, we shall see how to Add Swagger OpenAPI in Node.js and Express API. Swagger or OpenAPI describes the standards and specifications for the RESTFul API description.

These specifications are an attempt to create a universal and language agnostic description for describing the REST API.

In this article, we shall see below overall aspects,

Node.js express API can use OpenAPI V3.0 specifications which are more generic guidelines and specifications around how the API documentation should be generated.

Swagger provides the advantage of understanding and consuming the RESTFule API (for developers ).

Getting started – Add Swagger OpenAPI in Node.js

Add Swagger OpenAPI in Node.js is easy and can be performed using below high-level steps discussed,

Create your Node + Express project and perform NPM install.

Install node package called swagger-ui-express using NPM as below,

npm install swagger-ui-express --save

Install node package called swagger-jsdoc using NPM as below,

npm install swagger-jsdoc --save

Please enable the Swagger module in the API pipeline,

Enable Swagger module’s in the API pipeline in App.js as below,

const swaggerUi = require("swagger-ui-express");

const swaggerJsondoc = require("swagger-jsdoc");

Let’s define a simple GET API

Let’s define a simple GET API that returns a string as a response to the request.

Add below GET method in the App.js as below,


app.get("/hello", (req, res) => {
  res.json("Hello world!");
});


Add API level Global metadata

API level global data can be defined using Info object with details like Title, Version, or Description details.

Below is the list of API level documentation elements that can be specified,

  • Title
  • Version
  • Description
  • Contact
  • License details

const options = {
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "TheCodebuzz API",
      version: "1.0.0",
      description:
        "Thecodebuzz test service to demo how to document your API",
      license: {
        name: "MIT",
        url: "https://www.thecodebuzz.com"
      },
      contact: {
        name: "TheCodeBuzz",
        url: "https://www.thecodebuzz.com",
        email: "[email protected]"
      }
    },
    servers: [
      {
        url: "http://localhost:3000/"
      }
    ]
  },
  apis: []
};

Add Swagger UI Setup

Add Swagger UI as middleware in the express API pipeline.

const specs = swaggerJsondoc(options);
app.use("/docs", swaggerUi.serve);


app.get(
  "/docs",
  swaggerUi.setup(specs, {
    explorer: true
  })
);

Launch Swagger URL

Swagger URL can be launched here by using http://localhost:3000/docs

Swagger Node js

Add REST method level description

Let’s define api-method-docs.js which contains the REST method description as per the supported schema of Swagger/OpenAPI v3.0.

/**
 * @swagger
 * tags:
 *   name: Hello
 *   description: Greetings API from TheCodeBUzz
 */

/**
 * @swagger
 * path:
 *  /hello:
 *    get:
 *      summary: Get greeting message from TheCodebuzz
 *      responses:
 *        "200":
 *          description: GET reponse from API
 *          content:
 *            application/json:
 *              schema:
 *                type: string
 */


Above API level description can be defined in the api-method-doc.js as below,

  apis: ["./ api-method-doc.js"]

Please see below updated data,

const options = {
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "TheCodebuzz API",
      version: "1.0.0",
      description:
        "Thecodebuzz test service to demo how to document your API",
      license: {
        name: "MIT",
        url: "https://www.thecodebuzz.com"
      },
      contact: {
        name: "TheCodeBuzz",
        url: "https://www.thecodebuzz.com",
        email: "infoATthecodebuzz.com"
      }
    },
    servers: [
      {
        url: "http://localhost:3000/"
      }
    ]
  },
  apis: ["./api-doc.js"]
};

Please relaunch your API with the above changes.

Once launched, you shall see the GET method level API description below,

Add Swagger Express API

Let’s execute the GET API from Swagger UI. You see Swagger GET API returns your expected result.

Add Swagger OpenAPI to Nodejs and Express API

That’s All.

Now you can use the above technique to add API documentation for POST, PUT, DELETE methods as required.

References:

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.

Summary

Its simple to enable Swagger OpenAPI documentation in the Node js. Good API documentation helps reduce dependencies and provides the advantage of understanding the REST API(for developers) consuming API. It provides easy-ready API documentation and providing details of the capabilities a service/API provides.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *