Building a Swagger-Enabled Node.js API with Express

Introduction to Swagger in Node.js

Swagger is a powerful tool for designing, building, and documenting APIs. It provides a standardized way to describe RESTful APIs, making it easier for developers to understand, consume, and interact with API endpoints. In the context of Node.js, Swagger can be particularly useful for creating documentation that is both human-readable and machine-readable.

Key Components of Swagger

Swagger Specification/OpenAPI: The Swagger Specification, now known as the OpenAPI Specification, is a standard for describing RESTful APIs. It defines a format for documenting the structure and behavior of APIs in a machine-readable manner.

The specification uses JSON or YAML to describe API endpoints, request/response formats, parameters, authentication methods, and more.

Swagger UI: Swagger UI is a user-friendly interface that visualizes and interacts with the Swagger/OpenAPI documentation. It allows developers to explore the API, test endpoints and understand the expected request and response formats.

The UI is automatically generated based on the Swagger Specification, providing an interactive way to work with the API.

Swagger Codegen: Swagger Codegen is a tool that generates client libraries, server stubs, and API documentation based on the Swagger Specification. This can be particularly helpful for maintaining consistency between the server and client components of an API.

Integrating Swagger in a Node.js API

To integrate Swagger into a Node.js API, you can follow these step-by-step:

Step 1. Install Necessary Packages

Use npm to install the two required packages, such as express, swagger-jsdoc, and swagger-ui-express.

1. Swagger-jsdoc

npm install swagger-jsdoc --save

2. Swagger-ui-express

npm install swagger-ui-express --save

Go to the project folder and open the terminal to install the required packages.

Install packages

Picture 1. npm install swagger-jsdoc swagger-ui-express --save

After installation, you can check whether the package.json package was added or not.

Swagger- jsdoc'

Picture 2. installed "swagger-jsdoc": "^6.2.8",and "swagger-ui-express": "^5.0.0"

Step 2. Create Swagger Configuration

Write a Swagger configuration file that describes the API using JSDoc comments in the code. This configuration includes information such as API title, version, paths, parameters, and responses.

index.js

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Student Management System',
      version: '1.0.0',
      description: 'Student Management System covered Create, Read, Update, and Delete operations using a Node.js API',
    },  
    servers:[
      {url:'http://localhost:5000/api'}, //you can change you server url
    ],
  },

  apis: ['./routes/*.js'], //you can change you swagger path
};

Step 3. Integrate Swagger Middleware

Use middleware packages like swagger-jsdoc and swagger-ui-express to integrate Swagger into your Express.js application. This middleware dynamically generates the Swagger Specification and serves the Swagger UI.

index.js

1. Import the required middleware packages.

const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');

2 . Initialize Swagger-jsdoc.

const specs = swaggerJsdoc(options);

3. Serve Swagger documentation using Swagger UI.

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

Step 4. Define API Routes

Define the API routes using Express.js as usual. Swagger will automatically pick up the route information from the code comments.

Add the Swagger in studentRoute.js

1. API route : router.get("/student", getAllStudents);

Get all students

/**
 * @swagger
 * /student:
 *   get:
 *     summary: Get a list of all students
 *     tags: [Students]
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       400:
 *         description: Bad Request
 *         content:
 *          application/json:
 *            example:
 *             error:
 *              message: "Bad Request"
 */
//Get All Students
router.get("/student", getAllStudents);

2. API route: router.get("/student/:id", getStudent);

 Get the Student by ID

/**
 * @swagger
 * /student/{id}:
 *   get:
 *     summary: Get a student by ID
 *     tags: [Students]
 *     parameters:
 *       - name: id
 *         in: path
 *         required: true
 *         description: The ID of the student
 *         schema:
 *           type: string
 *         example:
 *             658918e852a0131af4c0aab1
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       404:
 *         description: Student not found
 */


//Get the Student
router.get("/student/:id", getStudent);

3. API route: router.post("/student", createStudent);

 Create a new student

/**
 * @swagger
 * /student:
 *   post:
 *     summary: Create a new student
 *     tags: [Students]
 *     requestBody:
 *       description: Student object to be added
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               address:
 *                 type: string
 *               dateOfBirth:
 *                 type: date
 *               gender:
 *                 type: string
 *               phoneNum:
 *                 type: integer
 *             example:
 *                name: "John Doe"
 *                address: "Colombo - Srilanka "
 *                dateOfBirth: 07/14/1990
 *                gender: "male"
 *                phoneNum: 01145252525
 *     responses:
 *       201:
 *         description: Successful response
 *         content:
 *           application/json:
 *             example:
 *               data: [{}]
 *       400:
 *         description: Invalid request
 */


//Create Student
router.post("/student", createStudent);

4. API route: router.put("/student/:id", updateStudent);

Update a student by ID

/**
 * @swagger
 * /student/{id}:
 *   put:
 *     summary: Update a student by ID
 *     description: Update the details of a student by providing the student ID.
 *     tags: [Students]
 *     parameters:
 *       - in: path
 *         name: id
 *         description: The ID of the student to be updated.
 *         required: true
 *         schema:
 *           type: string
 *     requestBody:
 *       description: Updated student information
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               address:
 *                 type: string
 *               dateOfBirth:
 *                 type: string
 *                 format: date
 *               gender:
 *                 type: string
 *               phoneNum:
 *                 type: integer
 *     responses:
 *       200:
 *         description: Successful update
 *         content:
 *           application/json:
 *             example:
 *               message: 'Student updated successfully'
 *       404:
 *         description: Student not found
 *         content:
 *           application/json:
 *             example:
 *               message: 'Student not found'
 */


//put the Student
router.put("/student/:id", updateStudent);

5. API route: router.delete("/student/:id", deleteStudent);

Delete a student by ID

/**
 * @swagger
 * /student/{id}:
 *   delete:
 *     summary: Delete a student by ID
 *     tags: [Students]
 *     parameters:
 *       - name: id
 *         in: path
 *         required: true
 *         description: The ID of the student
 *         schema:
 *           type: integer
 *         example:
 *             658918e852a0131af4c0aab1
 *     responses:
 *       204:
 *         description: Student deleted successfully
 *       404:
 *         description: Student not found
 */
//Delete the Student
router.delete("/student/:id", deleteStudent);

Step 5. Run The Application

  1. Start the Node.js application, npm start 
  2. Access the Swagger documentation by visiting the specified endpoint, usually /api-docs or a custom path. Example:  http://localhost:5000/api-docs/

Following these steps, you can enhance your Node.js API with interactive and well-documented Swagger/OpenAPI documentation, making it easier for developers to understand, test, and integrate with your API.

1. Go to the swagger path  http://localhost:5000/api-docs/

Student management system

Picture 3. Now you can see the Swagger UI.

2. Click on the Try it out button.

GET

Picture 4. Click on the GET method. Inside of dialog box, you can click on the Try it out button, 

3. Click on the Execute button, and get the response.

Execute

Picture 5. Click on the Execute button

4 Get the Response.

Code details

Picture 6. Get the Response with success

Summary 

The guide illustrates the step-by-step process of building a Swagger-enabled Node.js API using Express. The integration of Swagger into a Node.js API involves installing necessary packages, creating a Swagger configuration file, and defining API routes using Express.js.

The guide provides detailed code examples for each step, emphasizing the use of Swagger annotations in JSDoc comments to automatically generate interactive Swagger documentation. The final section instructs how to run the application and access the Swagger documentation through Swagger UI, allowing developers to understand, test, and interact with the API seamlessly. The provided images demonstrate the steps visually, highlighting the Swagger UI and the execution of API requests.


Similar Articles
Orfium Sri Lanka
Globally based Software Developing & Data Processing Company