/ Node

REST API with Node and Express

Hi Everyone! :) Today I will go over building a simple REST API using Node and Express to undertand its functionality and implementation!
REST APIs are definitely popular these days. They have eased the process of sending, receiving, storing information on servers and also building scalable applications.

It is now possible to build Microservices that perform a single operation, which leads to a group of microcervices working together as a team to run one big application---> like Amazon Retail! The cart, total amount calculation, tax calculation, all are individual microservices standing independantly but exchanging info through REST APIs to create one experince for their customers :)

I will be using Express, a framework of Node which enables us to write business logic in javascript. We will understand it a bit more, while we go through building a simple REST API together.

What is REST(Representaional State Tranfer)?. Which means, user data will no longer be stored on the servers. This restriction is called 'Statelessness'.
Every time an HTTP request is made from client, it contains all the required information to complete the request. It does not rely on previous requests.

Think of scenario where you are keeping track of your pet dogs getting vaccinated in your family after adoption! (Assuming you are a dog person :P) How would you build an API for this?

  1. You would need to access stored data.
  2. Return requested info
  3. Update data when your pet is vaccinated
  4. Deleting record if necessary

Lets begin.

  1. Create a folder for your project. Cd into your folder using Terminal/cmd

  2. Install node and express on your machine.
    Please refer below link if you haven't :
    Node
    Express
    Run:
    $ npm init
    $ npm install express --save
    This will create a package.json file inside. Package.json's main objective is to store dependencies for your project, like express in this case. It will also store your initial file to execute. I have named mine app.js
    packagejson

  3. Create app.js file at root of your directory. This is where our main logic will reside. Type the code given below.

    var express = require("express");
    var app = express();

    app.listen(3000,() => {
    console.log("Started on PORT 3000");
    })

  • We are importing express into our project.
  • Then initializing it to a variable called 'app'
  • Our app is listening to port 3000, so that when we hit the endpoint http://localhost:3000, we will see results
  1. To run your app, type $ node app.js
    app_running

  2. A server receives an HTTP request in a specific format, which it understands, performs required action and returns results to the client.

GET: Request to return data
POST: Request to send data
PUT: Request to update data
DELETE: Request to delete data

Let's create a GET request
Paste the below code in your app.js file :

var dogsArr = [];
app.get("/dogs", (req, res, next) => {
    res.json(dogsArr);
   });

We have created a 'dogsArr' array to store our information.
This function allows the express app to use '/dogs' url to trigger the callback that follows. The callback function accepts 3 parameters, req - carries information about the request; res - carries information about the response.

Run your app using $ node app.js in Terminal

  1. Viewing Results
    Once you hit http://localhost:3000 you will see an empty array.
    getInitial
    Or we could use Postman to test our routes.
    getPostManInitial

  2. POST request
    A post request sends data to the server from the client. We will be sending data in the form of a json object. For a POST request, we require a boody parser. In express, a body-parser is type of middleware required to extract the body sent through a request and save it in a json format.

Install it using below command :
npm install body-parser --save

Paste the below code to initialize body-parser:
const bodyParser = require("body-parser");
app.use(bodyParser.json())

Paste the below code for implementing POST request :
app.post('/dogs', function(req, res) {
var dog = req.body;
console.log(dog);
dogsArr.push(dog); //Push data into array
res.send("Dog added!");
});

This allows the url '/dogs' to return data stored in our dogsArr array.
I would prefer using postman to make this request, as it is easier to handle.
Go to your 'body' tab in Postman and paste the below JSON object :
{
"id": 1,
"dog": "Golder Retriever",
"vaccine": 0
},
{
"id": 2,
"dog": "Pug",
"vaccine": 0
}
It is very important to structure your JSON object carefully. Make sure you have an id associated with every entry. This makes it easier to peform CRUD operations.
postPostman

Also change the request to POST, which was previously set to GET
Hit Send.
postResult
You will see the response that we had set in our POST request.

Now, if you run a GET request, you can see data that we had sent previously :
postgetResult

Lets add another to our array with id 2:
addsecondEntry

  1. PUT request
    Now that we have our GET and POST request implemented, lets move on to updating data. Lets consider that our Pug is now vaccinated and we need to update our entries. Esentially, we need to change the parameter 'vaccine' to 1
    Paste the below code in your app.js :

app.put("/dogs/:dogsId", (req, res, next)=>{
dogsArr.forEach(ele=>{
console.log(ele);
if (ele.id == req.params.dogsId)
{
console.log(ele.id);
ele.vaccine = 1;
}
});
res.json({
message: "Completed a task!",
dogsArr : dogsArr
});
});

We are using the url '/dogs/:dogsId' where dogsId is the id which we would like to update.
We loop through each and every entry in our array and find the id which we are searching for. Once we find it, we update vaccine to 1.
We are also printing our response, using res.json() and updated array.
putPostman

  1. DELETE request
    We have learnt how to create, read and update data.
    But what if we need to delete an entry? Consider a scenario where your friend really liked your Pug and now you have decided to gift it to her! That also means, entry needs to be removed from your side.
    Implement the DELETE request as show below :

app.delete("/dogs/:dogsId", (req, res, next)=>{
var index;
dogsArr.forEach(ele=>{
if (ele.id == req.params.dogsId)
{
index = ele.id;
}
});

dogsArr.splice(index - 1,1);
res.json({
  message: "Completed a task!",
  dogsArr : dogsArr
});

});

This is similar to PUT request, but only difference is that we are using splice() function to remove the entry and update our array.
deletePostman

Now, we we send a GET request, and it should return only 1 entry of the Golden Retriever:
lastgetPostman

Yay!:) You have successfully deleted the required entry!

This is a simple implementation of how a REST API works. APIs are a set of rules/protocols(HTTP Protocols) which enable us to exchange information between our services. As long as apps and devices implement HTTP protocol, we can receive data from them. I will get into more details about the structure of routes in my next article! Feel free to clone my repo on GitHub, which contains above implementation and play with it to create something bigger and better. :)

REST API with Node and Express
Share this

Subscribe to Rujuta Mahindrakar