REST or RESTful stands for REpresentational State Transfer. It is an architectural style as well as an approach for communications purpose that is often used in various web services development. In simpler terms, it is an application program interface (API) which 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:
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.
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:
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.
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:
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:
Here 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 hereand click on ‘Add to Chrome’.
Once 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.
Now, 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.
If 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.
This 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.
Now, let’s send a GET request for our final list of books.
As 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.
#node-js #rest #api #web-development