In this article, we’ll cover up how to build a simple nodejs REST APIs using Swagger,Express and MySQL.
What is swagger?
Swagger is a set of open-source tools built around the OpenAPI Specification.
OpenAPI Specification is an API description format for REST APIs. An OpenAPI file allows you to describe , produce, consume, and visualize RRSTful web services.
What is Express Js?
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.
What is MySQL?
MySQL is an Open Source SQL database management system.MySQL server works in client/server or embedded systems.
What is REST API?
REST stands for Representational State Transfer.It is a set of standards for web services.An API is an interface that software programs use to communicate with each other.
HTTP requests utilize by REST API are :
- GET − Provides read-only access to a resource and retrieving of data.
 - PUT − Creates a new resource.
 - DELETE − Removes a resource.
 - POST − Updates an existing resource.
 
Settup/Installation
First, you need to create your project directory. Next, open the terminal and navigate to your project directory. Once there, you need to call npm using the below command:
npm init -y
You need to install the following dependencies:
- express: NodeJs Framework.
 - swagger-ui-express: For serving the swagger user interface in our API.
 - swagger-jsdoc : For generating swagger doc based on JSDoc.
 - body-parser: Incoming JavaScript applications will be transformed into JavaScript objects using this dependency.
 - nodemon: For restarting the development server in case of any change.
 - mysql: For mysql database configuration:
 
Install using the following command:
npm install express swagger-ui-express swagger-jsdoc body-parser nodemon mysql
Project Structure
The following image represent the nodeJs Project structure:

- Under the config  folder, we’ll create the db.
config.js file with the following contents: 
const { createPool } = require("mysql");
/** Connection pool creation - START */
const db = createPool({
  port: 3306,
  host: "localhost",
  user: "root",
  password: "",
  database: "employee",
  connectionLimit: 10,
});
/** Connection pool creation - END */
module.exports = db;
- Create an index.js file inside the root folder and add the below code:
 
const express = require("express");
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const app = express();
const bodyParser = require("body-parser");
const employeeRoutes = require("./routes/addEmployee.routes");
app.use(bodyParser.json());
/** Swagger Initialization - START */
const swaggerOption = {
  swaggerDefinition: (swaggerJsdoc.Options = {
    info: {
      version : "3.0.0",
      title: "Employee",
      description: "API documentation",
      contact: {
        name: "Developer",
      },
      servers: ["http://localhost:3002/"],
    },
  }),
  apis: ["index.js", "./routes/*.js"],
};
const swaggerDocs = swaggerJsdoc(swaggerOption);
app.use("/rest-api", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
/** Swagger Initialization - END */
/**  defining an endpoint */
app.use("/employee", employeeRoutes);
/**  starting the server */
app.listen(3002, () => {
  console.log("Port no. is 3002");
});
- Now we need to create a routes file under the routes folder to link with the controller i.e,routes/addEmployee.routes.js
 
const empController = require("../controller/addEmployee.controller");
var express = require("express");
var router = express.Router();
router.post("/add-emp", empController.addEmp);
/**
 * @swagger
 * /employee/add-emp:
 *   post:
 *      description: Used to add employee
 *      tags:
 *          - Add Employee
 *      parameters:
 *          - in: body
 *            name: Add Employee
 *            description: Employee data
 *            schema:
 *              type: object
 *              required:
 *                 - name
 *                 - empID
 *                 - phone
 *              properties:
 *                  name:
 *                      type: string
 *                      minLength: 1
 *                      maxLength: 1000
 *                      example: Tina
 *                  empID:
 *                      type: string
 *                      minLength: 1
 *                      maxLength: 1000
 *                      example: emp123
 *                  phone:
 *                      type: integer
 *                      example: 1234567896
 *      responses:
 *          '200':
 *              description: Resource added successfully
 *          '500':
 *              description: Internal server error
 *          '400':
 *              description: Bad request
 */
 router.get("/get-all-emp", empController.getAllEmp);
 /**
  * @swagger
  * /employee/get-all-emp:
  *   get:
  *      description: Used to get all employee
  *      tags:
  *          - Get all employee
  *      responses:
  *          '200':
  *              description: Resource added successfully
  *          '500':
  *              description: Internal server error
  *          '400':
  *              description: Bad request
  */
  router.put("/edit-emp", empController.editEmp);
  /**
   * @swagger
   * /employee/edit-emp:
   *   put:
   *      description: Used to dilike post
   *      tags:
   *          - Edit employee
   *      parameters:
   *          - in: body
   *            name: Post
   *            description: Post data
   *            schema:
   *              type: object
   *              properties:
   *                  name:
   *                      type: string
   *                      minLength: 1
   *                      maxLength: 1000
   *                      example: Tina
   *                  empID:
   *                      type: string
   *                      minLength: 1
   *                      maxLength: 1000
   *                      example: emp123
   *                  phone:
   *                      type: integer
   *                      example: 1234567896
   *      responses:
   *          '200':
   *              description: Resource added successfully
   *          '500':
   *              description: Internal server error
   *          '400':
   *              description: Bad request
   */
  router.delete("/delete-emp", empController.deleteEmp);
  /**
   * @swagger
   * /employee/delete-emp:
   *   delete:
   *      description: Used to delete employee
   *      tags:
   *          - Delete employee
   *      parameters:
   *          - in: query
   *            name: id
   *            type: integer
   *            description: id
   *            required: true
   *      responses:
   *          '200':
   *              description: Resource added successfully
   *          '500':
   *              description: Internal server error
   *          '400':
   *              description: Bad request
   */ 
module.exports = router;
- Let’s create a controller file under the controller folder to handle all the logic behind validating request parameters, queries, and Sending Responses with correct codes i.e,controller/addEmployee.controller.js
 
const empService = require("../services/addEmployee.service");
exports.addEmp = (req, res, next) => {
  const data = {
    name: req.body.name,
    empID: req.body.empID,
    phone: req.body.phone,
  };
  empService.addEmpPost(data, (error, results) => {
    if (error) {
      console.log(error);
      return res.status(400).send({ success: 0, data: "Bad request" });
    }
    return res.status(200).send({
      success: 1,
      data: results,
    });
  });
};
exports.getAllEmp = (req, res, next) => {
    const data = {};
    empService.getAllEmp(data, (error, results) => {
      if (error) {
        console.log(error);
        return res.status(400).send({ success: 0, data: "Bad request" });
      }
      return res.status(200).send({
        success: 1,
        data: results,
      });
    });
  };
  exports.editEmp = (req, res, next) => {
    const data = {
        name: req.body.name,
        empID: req.body.empID,
        phone: req.body.phone,
    };
    empService.editEmp(data, (error, results) => {
      if (error) {
        console.log(error);
        return res.status(400).send({ success: 0, data: "Bad request" });
      }
      return res.status(200).send({
        success: 1,
        data: results,
      });
    });
  };
  exports.deleteEmp = (req, res, next) => {
    const data = {
      id: req.query.id,
    };
    empService.deleteEmp(data, (error, results) => {
      if (error) {
        console.log(error);
        return res.status(400).send({ success: 0, data: "Bad request" });
      }
      return res.status(200).send({
        success: 1,
        data: results,
      });
    });
  };
- Create the service file under the services folder with the following database query i.e, services/addEmployee.service.js
 
const db = require("../config/db.config");
exports.addEmpPost = (data, callback) => {
  db.query(
    `INSERT INTO employee (name, empID, phone)
    VALUES (?, ?, ?)`,
    [data.name, data.empID, data.phone],
    (error, results, fields) => {
      if (error) {
        return callback(error);
      }
      return callback(null, "Employee added successfully");
    }
  );
};
exports.getAllEmp = (data, callback) => {
    db.query(
      `SELECT p.* FROM employee AS p`,
      [],
      (error, results, fields) => {
        if (error) {
          return callback(error);
        }
        return callback(null, results);
      }
    );
  };
  exports.editEmp = (data, callback) => {
    db.query(
      `UPDATE  employee
      SET 
      name =  '${data.name}',
      empID = '${data.empID}',
      phone = '${data.phone}'
      WHERE 
      empID = ?`,
      [data.empID],
      (error, results, fields) => {
        if (error) {
          return callback(error);
        }
        if (results.affectedRows === 1) {
          return callback(null, `Updated Successful`);
        } else {
          return callback(new Error("Invalid post"));
        }
      }
    );
  };
  exports.deleteEmp = (data, callback) => {
    db.query(
      `DELETE FROM employee 
      WHERE id = ?`,
      [data.id],
      (error, results, fields) => {
        if (error) {
          return callback(error);
        }
        if (results.affectedRows === 1) {
          return callback(null, `Employee Deleted Successfully`);
        } else {
          return callback(new Error("Invalid post"));
        }
      }
    );
  };
- Now run npm start command in your terminal and try to access http://localhost:3002/rest-api :
 


As you can see the output now.

great post, very useful .