Mastering Node.js (19 Blogs) Become a Certified Professional

Know how to build REST API with Node.js from scratch

Last updated on Jul 11,2023 83.1K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...
2 / 7 Blog from Node.Js Fundamentals

Since the invention of WWW, various web technologies like RPC or SOAP were used to create and implement web services. But these technologies used heavy definitions for handling any communication task. Thus, REST was developed which helped in reducing the complexities and provided an architectural style in order to design the network-based application. Since Node.js technology is revolutionizing the server for the front-end developers, in this article I will be demonstrating the process of Building REST API with Node.js from scratch.

Below are the topics that I will be covering in this article:

What is REST API?

REST or RESTful stands for REpresentational State Transfer. It is an architectural style as well as an approach for communications purposes that is often used in various web services development. In simpler terms, it is an application program interface (API) that makes use of the HTTP requests to GET, PUT, POST and DELETE the data over WWW.

REST architectural style helps in leveraging the lesser use of bandwidth which makes an application more suitable for the internet. It is often regarded as the “language of the internet”. It is completely based on the resources where each and every component is regarded as a component and a single resource is accessible through a common interface using the standard HTTP method.

To understand better, let’s dive a little deeper and see how exactly does a REST API work. Basically, the REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but requires a lot of effort to be built from the very scratch.

The main functions used in any REST-based architecture are:

  • GET − Provides read-only access to a resource.
  • PUT − Creates a new resource.
  • DELETE − Removes a resource.
  • POST − Updates an existing resource or creates a new resource.

But all who claims cannot be referred to as RESTful API. In order to be regarded as a RESTful API, your application must satisfy certain constraints or principles. In the next section of this article on Building a REST API using Node.js, I will be talking about these principles in detail.

Principles of REST

Well, there are six ground principles laid down by Dr. Fielding who was the one to define the REST API design in 2000. Below are the six guiding principles of REST:

  1. Stateless
    Requests sent from a client to the server contains all the necessary information that is required to completely understand it. It can be a part of the URI, query-string parameters, body, or even headers. The URI is used for uniquely identifying the resource and the body holds the state of the requesting resource. Once the processing is done by the server, an appropriate response is sent back to the client through headers, status or response body.
  2. Client-Server
    It has a uniform interface that separates the clients from the servers. Separating the concerns helps in improving the user interface’s portability across multiple platforms as well as enhance the scalability of the server components.
  3. Uniform Interface
    To obtain the uniformity throughout the application, REST has defined four interface constraints which are:

    • Resource identification
    • Resource Manipulation using representations
    • Self-descriptive messages
    • Hypermedia as the engine of application state
  4. Cacheable
    In order to provide a better performance, the applications are often made cacheable. It is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is defined as cacheable, then the client cache can reuse the response data for equivalent responses in the future. It also helps in preventing the reuse of the stale data.
  5. Layered system
    The layered system architecture allows an application to be more stable by limiting component behavior.  This architecture enables load balancing and provides shared caches for promoting scalability. The layered architecture also helps in enhancing the application’s security as components in each layer cannot interact beyond the next immediate layer they are in.
  6. Code on demand
    Code on Demand is an optional constraint and is used the least. It permits a clients code or applets to be downloaded and extended via the interface to be used within the application. In essence, it simplifies the clients by creating a smart application which doesn’t rely on its own code structure.

Now that you know what is a REST API and what all you need to mind in order to deliver an efficient application, let’s dive deeper and see the process of building REST API using Node.js.

Practical Demonstration: Building REST API using Node.js

Here, we will be creating a simple CRUD REST application for Library Management using Node.js and Express.js. To build this application, you will need to install the following:

  1. Node.js
  2. Express.js
  3. Joi
  4. nodemon (Node Monitor)

In this example, I will be using the WebStorm IDE to write and execute the codes. You can use any IDE or code editor according to your choice. So, let’s get started.

First, you need to create your project directory. Next, open the command prompt and navigate to your project directory. Once there, you need to call npm using the below command:

npm init

When you hit enter, Node.js will ask you to enter some details to build the .json file such as:

cmd npm - Building REST API with Node.js - EdurekaHere you can define your entry point along with several other information. For this demo, I will be using script.js as an entry point. Next, we will be installing Express.js using the below command:

npm i express

Finally, I will be installing a node monitoring package called nodemon. It keeps a watch on all the files with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to restart the Node.js server each time any changes are made. nodemon will implicitly detect the changes and restart the server for you.

npm i -g nodemon

package.json


{
"name": "samplerestapi",
"version": "1.0.0",
"description": "Edureka REST API with Node.js",
"main": "script.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Edureka",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"joi": "^13.1.0"
}
}

script.js


const express = require('express');
const Joi = require('joi'); //used for validation
const app = express();
app.use(express.json());

const books = [
{title: 'Harry Potter', id: 1},
{title: 'Twilight', id: 2},
{title: 'Lorien Legacies', id: 3}
]

//READ Request Handlers
app.get('/', (req, res) => {
res.send('Welcome to Edurekas REST API with Node.js Tutorial!!');
});

app.get('/api/books', (req,res)=> {
res.send(books);
});

app.get('/api/books/:id', (req, res) => {
const book = books.find(c => c.id === parseInt(req.params.id));

if (!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Ooops... Cant find what you are looking for!</h2>');
res.send(book);
});

//CREATE Request Handler
app.post('/api/books', (req, res)=> {

const { error } = validateBook(req.body);
if (error){
res.status(400).send(error.details[0].message)
return;
}
const book = {
id: books.length + 1,
title: req.body.title
};
books.push(book);
res.send(book);
});

//UPDATE Request Handler
app.put('/api/books/:id', (req, res) => {
const book = books.find(c=> c.id === parseInt(req.params.id));
if (!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Not Found!! </h2>');

const { error } = validateBook(req.body);
if (error){
res.status(400).send(error.details[0].message);
return;
}

book.title = req.body.title;
res.send(book);
});

//DELETE Request Handler
app.delete('/api/books/:id', (req, res) => {

const book = books.find( c=> c.id === parseInt(req.params.id));
if(!book) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;"> Not Found!! </h2>');

const index = books.indexOf(book);
books.splice(index,1);

res.send(book);
});

function validateBook(book) {
const schema = {
title: Joi.string().min(3).required()
};
return Joi.validate(book, schema);

}

//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

Now, the next step is to check whether the handlers are working properly or not. For that, we will use a Chrome extension called Postman. To install Postman you can visit here and click on ‘Add to Chrome’.

postman - Building REST API with Node.js - EdurekaOnce you have successfully installed Postman, open it and start testing your application. So, let’s start off by testing our GET method. Now, in order to do that you need to select GET from the drop-down list, type in the defined URI and hit send. If your code is working fine, then you will see the list of all the books which we have added manually in our code. In the below picture, you can see how my result looks like.

GET - Building REST API with Node.js - EdurekaNow, let’s try adding a new book to our inventory list. For that, select ‘POST’ from the drop-down list and type in the defined URI for the POST method. Now, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as depicted in the below image. Now, in the text area, type in the title of your book as shown and hit send.

POST - Building REST API with Node.js - EdurekaIf your POST method is working fine, your response body will contain the book title along with the book id. Now, let’s try to update the book title. Currently, my book title is “Angels and Demons” which I will be updating to “Angels & Demons”. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT request’s  URI along with the book id you wish to update. Next in the ‘Body’,  type in the new book title and hit enter.

PUT - Building REST API with Node.js - EdurekaThis will give you a response with the book id and updated book title.

Finally, let’s send a ‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URI of the delete request handler along with the book details, you want to remove and hit enter. If your transaction is successful, you will see the complete details of the entry you have removed in the response body.DELETE - Building REST API with Node.js - Edureka

Now, let’s send a GET request for our final list of books.

GET ALL - Building REST API with Node.js - EdurekaAs you can see from the above screenshot, the response body contains a total of three books with the book id 3 missing as we have already deleted that entry.

With this, we come to an end of this article on Building REST API with Node.js. I tried to keep the concepts simple and crisp.  Now, if you want to get into more details of Node.js, you can check out my article on Node.js Tutorial.

If you found this “REST API with Node.js” relevant, check out the Node.js Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this REST API with Node.js and we will get back to you.

Upcoming Batches For Node.js Certification Training Course
Course NameDateDetails
Node.js Certification Training Course

Class Starts on 20th April,2024

20th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Know how to build REST API with Node.js from scratch

edureka.co