In this tutorial we will learn how to create RESTful APIs using Node.js and Express 4. Using Express 4 we can easily manage GET and POST requests. We have also used Mysql to Fetch and post data from database.

For demo we have created simple Book store app APIs. By using that we can Show, Add, Update & Delete Books data. Also showing the response data of api’s using postman.

SQL file can be found along with the downloaded code.

DOWNLOAD

Let’s start with installing dependencies and then the code,

Install dependencies

Will going to use following node modules for handling session.

  1. Express 4
  2. Body parser
  3. MySql

I have created a package.json file that will install all required dependencies. have a look,

package.json


{
"name": "Node-APIs",
"version": "0.0.1",
"main": "server.js",
"dependencies": {
"express": "^4.8.7",
"mysql":"^2.5.5",
"body-parser":"^1.12.0"
}
}

How to install dependencies?

By typing following command you can install dependencies,

npm install

Note : You must also have MySQL installed if you are working locally.

 

Initialization & Require

First will include require node modules and http server.
Also we have done connection of MySql for GET & POST data.

server.js


var app = require('express')(); // Express App include
var http = require('http').Server(app); // http server
var mysql = require('mysql'); // Mysql include
var bodyParser = require("body-parser"); // Body parser for fetch posted data
var connection = mysql.createConnection({ // Mysql Connection
host : 'localhost',
user : 'root',
password : '',
database : 'books',
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // Body parser use JSON data

 

Show List Of Books

Using below API we will fetch all books with it’s data.

server.js


app.get('/book',function(req,res){
var data = {
"error":1,
"Books":""
};


connection.query("SELECT * from book",function(err, rows, fields){
if(rows.length != 0){
data["error"] = 0;
data["Books"] = rows;
res.json(data);
}else{
data["Books"] = 'No books Found..';
res.json(data);
}
});
});

Get all books Response
Get all books Response

First will define route url (i.e : app.get(‘/book’,function()) ).

And then make sql query to fetch all book data using connection.query. That will fetch all book data and return as json. which you can see in above image.

 

Add New Book

Using below API we will add new book data to database.

server.js


app.post('/book',function(req,res){
var Bookname = req.body.bookname;
var Authorname = req.body.authorname;
var Price = req.body.price;
var data = {
"error":1,
"Books":""
};
if(!!Bookname && !!Authorname && !!Price){
connection.query("INSERT INTO book VALUES('',?,?,?)",[Bookname,Authorname,Price],function(err, rows, fields){
if(!!err){
data["Books"] = "Error Adding data";
}else{
data["error"] = 0;
data["Books"] = "Book Added Successfully";
}
res.json(data);
});
}else{
data["Books"] = "Please provide all required data (i.e : Bookname, Authorname, Price)";
res.json(data);
}
});

Add New Book Response
Add New Book Response

First will define route url (i.e : app.post(‘/book’,function()) ).

And then make sql query to add book data to database using connection.query. That will add book data and based on that return response as json. which you can see in above image.

 

Update Existing Book

Using below API we will update existing book data to database.

server.js


app.put('/book',function(req,res){
var Id = req.body.id;
var Bookname = req.body.bookname;
var Authorname = req.body.authorname;
var Price = req.body.price;
var data = {
"error":1,
"Books":""
};
if(!!Id && !!Bookname && !!Authorname && !!Price){
connection.query("UPDATE book SET BookName=?, AuthorName=?, Price=? WHERE id=?",[Bookname,Authorname,Price,Id],function(err, rows, fields){
if(!!err){
data["Books"] = "Error Updating data";
}else{
data["error"] = 0;
data["Books"] = "Updated Book Successfully";
}
res.json(data);
});
}else{
data["Books"] = "Please provide all required data (i.e : id, Bookname, Authorname, Price)";
res.json(data);
}
});

Update Existing Book Response
Update Existing Book Response

First will define route url (i.e : app.put(‘/book’,function()) ).

And then make sql query to update book data to database using connection.query. That will update book data and based on that return response as json. which you can see in above image.

 

Delete Existing Book

Using below API we will delete existing book data to database.

server.js


app.delete('/book',function(req,res){
var Id = req.body.id;
var data = {
"error":1,
"Books":""
};
if(!!Id){
connection.query("DELETE FROM book WHERE id=?",[Id],function(err, rows, fields){
if(!!err){
data["Books"] = "Error deleting data";
}else{
data["error"] = 0;
data["Books"] = "Delete Book Successfully";
}
res.json(data);
});
}else{
data["Books"] = "Please provide all required data (i.e : id )";
res.json(data);
}
});

Delete Existing Book Response
Delete Existing Book Response

First will define route url (i.e : app.delete(‘/book’,function()) ).

And then make sql query to delete book data to database using connection.query. That will delete book data and based on that return response as json. which you can see in above image.

 

How to run?

First check whether you have installed Node.js or not.
Then install all required dependencies (i.e : express, express-session & body-parser ) by typing following command in terminal,

npm install

Now, run the server using following command.

node server.js

And now go to postman and hit “localhost:8080/RoutesUrl″. for checking APIs.

 

Watch Video tutorial


 

26 Comments

  1. Actually this is not RESTful API.

    When routing REST API, you should not use verb in your domain

    for example, app.post(‘/deletebook’) -> app.delete(‘/book’) this is right way.

  2. Hi Inaam,

    Thanks for the excellent tutorial for creating RESTful API Using Node.js & Express 4.

    I tried using your tutorial as it is but got stuck at one place. For post/put requests, I am getting undefined request.body.

    Could you please suggest what could be the reason for this issue?

    Thanks in advance.

  3. Hi Inaam,

    Yes, I am already using Postman.

    Below are the steps that I follow overall –

    1. Downloaded the project from the git repo in your blog.
    2. Install Node.js, MySQL, Postman
    3. Create table in the MySQL myself ( I was not able to find sql script to do that in the source code)
    4. Run the command ‘npm install’
    5. Started the server using following command ‘node server.js’
    6, When I try to hit “localhost:8080/RoutesUrl″ in Postman gets below error –

    Cannot POST /RoutesUrl

    Further, I am passing the data in json format the way it is suggested in your blog. The get request is working fine and I am able to see the list of books. But for post/put requests, I am getting below error in the Postman –

    {
    “error”: 1,
    “Books”: “Please provide all required data (i.e : Bookname, Authorname, Price)”
    }

    In order to debug the issue, I placed some console.log() statements in server.js and notices that req.body is coming as undefined.

    1. Hi Neeraj,

      I have added sql file for this. By downloading latest code you will find that file.

      And for the process, all above till step 5 you did correct.
      for step 6 you need to call this URL in postman for post requests is ( i.e : http://localhost:8080/book ).
      And object you need to pass in raw tab is,
      {
      “bookname”:”newtestbook”,
      “authorname”:”boy”,
      “price”:”657″
      }
      And then you should get response like,
      {
      “error”: 0,
      “Books”: “Book Added Successfully”
      }

      By doing this steps it’s work fine for me. please check again with above mentioned description for step 6.

      Thanks.

  4. Hi, thank you for nice tutorial.

    One thing, API endpoint could be more RESTful/CRUD ?
    GET /books – for all books
    POST /books – add new one
    GET /books/{id} – for particular book
    DELETE /books/{id} – response HTTP 404 error code when book doesn’t exists
    PUT /books/{id}

    best regards

  5. Can anyOne suggest me how i can learn Node.js From Scratch … i need step by step guide where i should start and can become a professional Node Developer

  6. I am new to Node JS Sir,I am Followed your Full Process..For me..Get Api is Working..Other then that Post,Delete,Put Api are not working Sir

  7. Hi,
    I am new to Postman. Could you please tell me the required header for this? And the URL parameters? Only GET call is working, the rest have different (but not the desired) outputs based on the headers.
    Thanks.

    1. Hi khush,

      In header you need to pass “content-type” : “application/json” and in raw data tab you have to pass your data object. that you can see above images.
      Thanks.

      1. Thank you, that worked.

        Could you please also guide how to GET data based on ID? As in, get individual rows instead of the entire table.

      2. A.o.A!
        Dear! Please suggest me what I m doing wrong with this INSERT (POST) operation.
        url: http://localhost:8080/book
        Type: GET
        Header (key-value): “content-type” “application/json”
        raw:
        {
        “bookname”:”newtestbook”,
        “authorname”:”boy”,
        “price”:”657″
        }

        THEN ON CLICKING |SEND| Button , no result appears.. 🙁

        1. Everything looks fine except ‘Type’. that should be ‘POST’ instead ‘GET’. and raw data is like,
          raw:
          {
          “bookname”:”newtestbook”,
          “authorname”:”boy”,
          “price”:657
          }
          Thanks.

  8. if(rows.length != 0){
    ^
    TypeError: Cannot read property ‘length’ of undefined

    I am getting this error for app.get(‘/book’ api. What is the issue? I think rows is null but i don’t understand why it is being returned null. Please help

  9. Hi,

    I have everything setup and double checked all the code files but I’m getting an error trying to run the server.js app with node:

    /home/pi/NodeApps/NodeRestAPI/server.js:47
    connection.query(“INSERT INTO book
    ^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:414:25)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:134:18)
    at node.js:961:3

    I can access the database OK and perform select statements without issue so not sure what is going on here. I’m new to Node and Express.

    p.s. I’ve updated the script with the correct login details for my instance of MySQL and tested that in the console as well.

    Many thanks for any assistance.

    Cheers,
    Lee

    1. Hey can you please provide query which you were trying, otherwise its look fine. or else send me your file so that i can look in to that file and resolve your problem.
      Thanks.

  10. Thanks for the tutorial. It would have been slightly easier to get it working if you had mentioned somewhere in the post that the following line should be appended to server.js – to someone without any node / express experience, this is not obvious.

    http.listen(8080, function(){
    console.log(“Connected & Listen to port 8080”);
    });

Leave a Reply

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