Introduction

In this article, we are going to create a Web API with the help of node.js, Express, and MySQL. Web API is an application which serves HTTP based requests by different applications on different platforms, such as web, Windows, and mobile.
Requirements
  1. MySQL
  2. NodeJS
  3. Active Internet
  4. Postman Application
  5. Visual Studio Code
Step 1
Create a database in MySQL, named sampledb and use it.
  1. mysql> create database sampledb;
  2. mysql> use sampledb;
Step 2
Create a new table named employee.
  1. mysql> create table employee
  2. (
  3. id int primary key,
  4. name varchar(20),
  5. gender varchar(20),
  6. city varchar(20),
  7. salary int
  8. );
Step 3
Add some rows to the table.
  1. mysql> insert into employee values(1,'pankaj','male','delhi',15000);
  2. mysql> insert into employee values(2,'pooja','female','pune',25000);
Step 4
Open command prompt/cmd and navigate to the application folder, i.e., webapi.
C:\Users\Pankaj Singh\Desktop\webapi>
Step 5
Initialize the app with npm init,
C:\Users\Pankaj Singh\Desktop\webapi>npm init
Web API Using NodeJS+Express+MySql
Step 6
Now, add some Node modules, as mentioned below.
C:\Users\Pankaj Singh\Desktop\webapi>npm install express
C:\Users\Pankaj Singh\Desktop\webapi>npm install mysql
C:\Users\Pankaj Singh\Desktop\webapi>npm install body-parser
Step 7
Add a server.js file to the application.
C:\Users\Pankaj Singh\Desktop\webapi>null>server.js
Step 8
Open Visual Studio Code.
C:\Users\Pankaj Singh\Desktop\webapi>code .
Web API Using NodeJS+Express+MySql
Step 9
Our package.json file looks like this.
Web API Using NodeJS+Express+MySql
Step 10
Now, configure the server.js file. Basic Express app is as follows
  1. var express = require('express');
  2. var mysql = require('mysql');
  3. var bodyParser=require('body-parser');
  4. var urlencoderParser = bodyParser.urlencoded({extended:false});
  5. var app=express();
  6. var port = process.env.port||3000;
  7. //Api code here
  8. app.listen(port);
  9. console.log('Server is started on http://localhost:'+port);
Step 11
Add a connection to MySQL.
  1. //Mysql Connection
  2. var con = mysql.createConnection({
  3. host:'localhost',
  4. user:'root',
  5. password:'password0',
  6. database:'sampledb'
  7. });
Step 12
Now, add code for GET request on root “/api” . This route returns all the rows of employee table.
  1. //GET
  2. app.get('/api',function(req,res){
  3. var qry = "select * from employee";
  4. con.query(qry,function(err,rows){
  5. if(err)
  6. throw err;
  7. console.log(rows);
  8. res.json(rows);
  9. });
  10. });
Step 13
Add code for GET request with id on root “/api/<id>”. This route returns the row of employee table with the given id
  1. //GET with id
  2. app.get('/api/:id',function(req,res){
  3. var qry = "select * from employee where id="+req.params.id;
  4. con.query(qry,function(err,rows){
  5. if(err)
  6. throw err;
  7. console.log(rows[0]);
  8. res.json(rows[0]);
  9. });
  10. });
Step 14
Now, add code for POST request. In this request, we use urlencoderParser to read the body content of the request.
  1. //POST
  2. app.post('/api',urlencoderParser,function(req,res){
  3. var qry = "insert into employee values("+parseInt(req.body.id)+",'"+req.body.name+"','"+req.body.gender+"','"+req.body.city+"',"+parseInt(req.body.salary)+")";
  4. con.query(qry,function(err,rows){
  5. if(err)
  6. throw err;
  7. console.log("1 Row Added.");
  8. res.send("1 Row Added.")
  9. });
  10. });
Step 15
Now, add code for POST request. In this request, we use urlencoderParser to read the body content of the request.
  1. //PUT
  2. app.put('/api/:id',urlencoderParser,function(req,res){
  3. var qry = "update employee set name='"+req.body.name+"',gender='"+req.body.gender+"',city='"+req.body.city+"',salary="+parseInt(req.body.salary)+" where id="+parseInt(req.params.id);
  4. con.query(qry,function(err,rows){
  5. if(err)
  6. throw err;
  7. console.log("1 Row Updated.");
  8. res.send("1 Row Updated.")
  9. });
  10. });
Step 16
Add the code for DELETE Request.
  1. //DELETE
  2. app.delete('/api/:id',function(req,res){
  3. var qry = "delete from employee where id="+parseInt(req.params.id);
  4. con.query(qry,function(err,rows){
  5. if(err)
  6. throw err;
  7. console.log("1 Row Removed.");
  8. res.send("1 Row Removed.")
  9. });
  10. });
Step 17
The complete code is as follows.
  1. var express = require('express');
  2. var mysql = require('mysql');
  3. var bodyParser=require('body-parser');
  4. var urlencoderParser = bodyParser.urlencoded({extended:false});
  5. var app=express();
  6. var port = process.env.port||3000;
  7. //Api code here
  8. //Mysql Connection
  9. var con = mysql.createConnection({
  10. host:'localhost',
  11. user:'root',
  12. password:'password0',
  13. database:'sampledb'
  14. });
  15. //GET
  16. app.get('/api',function(req,res){
  17. var qry = "select * from employee";
  18. con.query(qry,function(err,rows){
  19. if(err)
  20. throw err;
  21. console.log(rows);
  22. res.json(rows);
  23. });
  24. });
  25. //GET with id
  26. app.get('/api/:id',function(req,res){
  27. var qry = "select * from employee where id="+req.params.id;
  28. con.query(qry,function(err,rows){
  29. if(err)
  30. throw err;
  31. console.log(rows[0]);
  32. res.json(rows[0]);
  33. });
  34. });
  35. //POST
  36. app.post('/api',urlencoderParser,function(req,res){
  37. var qry = "insert into employee values("+parseInt(req.body.id)+",'"+req.body.name+"','"+req.body.gender+"','"+req.body.city+"',"+parseInt(req.body.salary)+")";
  38. con.query(qry,function(err,rows){
  39. if(err)
  40. throw err;
  41. console.log("1 Row Added.");
  42. res.send("1 Row Added.")
  43. });
  44. });
  45. //PUT
  46. app.put('/api/:id',urlencoderParser,function(req,res){
  47. var qry = "update employee set name='"+req.body.name+"',gender='"+req.body.gender+"',city='"+req.body.city+"',salary="+parseInt(req.body.salary)+" where id="+parseInt(req.params.id);
  48. con.query(qry,function(err,rows){
  49. if(err)
  50. throw err;
  51. console.log("1 Row Updated.");
  52. res.send("1 Row Updated.")
  53. });
  54. });
  55. //DELETE
  56. app.delete('/api/:id',function(req,res){
  57. var qry = "delete from employee where id="+parseInt(req.params.id);
  58. con.query(qry,function(err,rows){
  59. if(err)
  60. throw err;
  61. console.log("1 Row Removed.");
  62. res.send("1 Row Removed.")
  63. });
  64. });
  65. app.listen(port);
  66. console.log('Server is started on http://localhost:'+port);
Step 18
Now, Run the API.
C:\Users\Pankaj Singh\Desktop\webapi>nodemon server.js
[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Server is started on http://localhost:3000
Step 19
Open Postman to test the API.
Web API Using NodeJS+Express+MySql
Step 20
Sending GET Request to API. In response, we get all the rows of the employee table as JSON data.
Web API Using NodeJS+Express+MySql
Step 21
Sending GET Request with Id to API. In response, we get all the row of the employee table with given id as JSON data.
Web API Using NodeJS+Express+MySql
Step 22
Sending POST Request with the body to API.
Web API Using NodeJS+Express+MySql
Step 23
Sending put request with the body to API.
Web API Using NodeJS+Express+MySql
Step 24
Sending put request with the body to API.
Web API Using NodeJS+Express+MySql