Introduction to Building RESTful APIs in Node.js
Updated: Nov 2, 2022
This is an introductory tutorial on creating REST API in Node.js from scratch. The post, followed by many more, will cover all the topics required for building such APIs with perfection. First, let us try to understand WHAT IS REST or RESTful API?
Quick Links -
What is REST
As per the definition provided in official documentation of RESTful API, REST stands for Representational State Transfer. It is an architectural style for distributed hypermedia systems, which was created by computer scientist Roy Fielding.
In simpler words, REST suggests to design an object of data requested by the client, and send the values of the object in response to the user.
For example, if a user is requesting for a weather report in Delhi at a certain locality and at a particular time, then we can create an object on the server side and send the state of the object to the user.
If a web service interface needs to be referred as RESTful, then it must fulfil some guiding principles and constraints of REST architecture. You can get more information about this on https://restfulapi.net/
If you are unable to understand this completely, then don’t worry. We'll gain clarity as we
move forward and start coding.
Methods of REST API
While working with web services, we work on CRUD Operations to deal with databases, where CRUD stands for
C = Create a record
R = Read a record
U = Update a record
D = Delete a record
However, REST and CRUD resemble each other as REST is a superset of CRUD. We can perform these operations in RESTful architecture with the help of http methods. So, CREATE of CRUD will be replaced by POST, READ by GET, UPDATE by PUT/PATCH and DELETE will remains DELETE.
| CRUD OPERATION | RESTFUL OPERATIONS |
---|---|---|
C | CREATE | POST |
R | READ | PUT |
U | UPDATE | PUT/PATCH |
D | DELETE | DELETE |
Hope we now understand the basic meaning of RESTful APIs. Let us understand the concept practically.
Coding GET API
To start with the coding, we first need to install required package. For now, let us only install express.
npm i express
Once done, let us create a JSON file, users.json, containing details about some users. So, our users.json looks like -
{
"user1" : {
"name" : "Tom",
"password" : "password1",
"profession" : "Professor",
"id": 1
},
"user2" : {
"name" : "Oswald",
"password" : "password2",
"profession" : "Librarian",
"id": 2
},
"user3" : {
"name" : "Micky",
"password" : "password3",
"profession" : "Student",
"id": 3
}
}
Next, we will be creating a server file and name it app.js. Our app.js will look like -
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/listUsers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log( data );
res.end( data );
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Let us understand the above mentioned code line by line.
In the first line, we have imported the express package by using require keyword. Express package is required to structure our web application by handling multiple different http requests.
var express = require('express');
In the next line of code, we have initialized the express by typing -
var app = express();
Then we have imported the fs package, which is a file system management module that helps us to work with files present in our system. Here, it will help us to work with the json file we have created.
var fs = require("fs");
Next, to perform operations on our data, we need to set up Routing. Each route has a HTTP method, url, and a handler function to handle the http request and responses. In our code, mentioned below, app.get( … ) acts as router (for the purpose of routing we discussed), where .get is the http method. Inside the app.get(), the ‘/listUsers’ is the URL defined explicitly and the function with parameters as req,res is the handler function to handle http requests (req) and responses (res).
app.get('/listUsers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err,
data) {
console.log( data );
res.end( data );
});
})
And finally, we have created a server using listen() method of express module.
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
After finishing with this, let us check for the output. To start the server, type the following command in command line -
node app.js
NOTE: app.js because it is the name of the file containing our server connectivity code.
After running the command, we get -
![](https://static.wixstatic.com/media/dca741_68c1dd13fbf0485b94270ac40dc20fd7~mv2.jpg/v1/fill/w_964,h_95,al_c,q_80,enc_auto/dca741_68c1dd13fbf0485b94270ac40dc20fd7~mv2.jpg)
Now, open Postman, select http method as GET and in the search bar, type - http://127.0.0.1:8081/listUsers
The Output produced, will be -
![](https://static.wixstatic.com/media/dca741_26df4dffe8f8443a99faa9fff6105c5e~mv2.jpg/v1/fill/w_980,h_602,al_c,q_85,usm_0.66_1.00_0.01,enc_auto/dca741_26df4dffe8f8443a99faa9fff6105c5e~mv2.jpg)
For those who do not know what POSTMAN is, you can refer to the following link -
Hope we now understand the basics of creating APIs in node.js.
Thank you.
Comments