Using Node.js to build REST APIs
Node.js is a platform for building server applications using JavaScript. The platform provides a way to create web applications and services that have to serve a large number of clients. One can quickly setup a basic server using Node.js that serves pages and APIs. In the last two posts, we saw how to get started with Node.js and how to serve pages and static content. In this post, we will see how to build some basic REST APIs using Node.js.
Express.js can be installed into using NPM. Run the following command to install express.js:
Start a command prompt, move to the newly created folder and install the NPM packages discussed above (express and body-parser). Open the file server.js in a text editor and add the following code to it:
Now we need to start the server on a port and setup body-parser on express.js. The following statements do this task:
Save this file and run the following command to start the Node.js server:
Let’s add an API to add a new city to the collection. It is going to be a POST API that checks for existence of the city by its name before adding the city. If the city is already present in the collection, it has to send an error to the client saying “City already exists”.
Similarly, we can define response to a PUT request using app.put method. Following API modifies entry of a city:
Download the entire source code of this article (Github).
What is REST?
REST (Representational State Transfer) is an architectural style for building scalable web services. Over the past few years, REST has gained widespread attention because of its ease of use when compared with SOAP. REST is extensively used by cloud providers, mobile app developers, in building Single Page Apps (SPAs) and many others to build scalable services. Following are the properties of a RESTful service:- Client-server based: REST provides separation of concerns between client and server by segregating responsibilities of the two pieces
- Stateless: Server doesn’t store any information about the client and hence every request is unique to the server
- Cacheable: Response of a REST API can be cached and used for subsequent responses to optimize behavior
- Uniform Interface: The clients don’t need to learn a new API to consume REST APIs. They need to be aware of the uniform interface standardized for REST and know format of the data to be set and received.
RESTful APIs Using Node.js
As Node.js runs server apps based on HTTP protocol and working with the Node.js API provides a way to directly interact with the HTTP verbs, the platform makes the process of building REST APIs easier. If you read the previous posts on Getting Started with Node.js and Serving HTML pages and static content using Node, we built the apps using the http module. Though the same module can be used to build REST services, it will be difficult while dealing with multiple HTTP verbs and parsing the objects from request body. Frameworks built on top of Node.js abstract this difficulty of dealing with the lower level APIs and provide easier ways to work with HTTP. Express.js is the most popular framework of the frameworks available for Node.js.A brief intro to Express.js
Express.js is a light weight framework built on top of Node.js and it provides abstractions to make our job of working with HTTP easier. Express also provides a way to add middle-wares to the pipeline. These middle-wares can be used to perform tasks like authentication, logging, and any other pre or, post processing logic that has to be executed with every request.Express.js can be installed into using NPM. Run the following command to install express.js:
> npm install expressWe also need to install body-parser to be able to read JSON data from the request body. Run the following command to install body-parser:
> npm install body-parser
Building some REST APIs using Node.js
We will build a simple set of APIs to perform GET, POST and PUT operations. Create a new folder and name it NodeRESTAPIs. In this folder, add a new file and name it server.js.Start a command prompt, move to the newly created folder and install the NPM packages discussed above (express and body-parser). Open the file server.js in a text editor and add the following code to it:
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var cities = [{name: 'Delhi', country: 'India'}, {name: 'New York', country: 'USA'}, {name: 'London', country:'England'}];
The first three statements get references of the modules and the last statement creates an in-memory collection on which we will perform the CRUD operations.Now we need to start the server on a port and setup body-parser on express.js. The following statements do this task:
var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.listen(3000, function(){ console.log("Listening on port 3000..."); });
Save this file and run the following command to start the Node.js server:
> node server.js
It starts the web server and logs the above message on the console. At this point, we won’t be able to surf anything from this application, as we didn’t create any endpoints yet. Let’s add an API that responds to GET request and returns all cities:app.get('/api/cities', function(request, response){
response.send(cities);
});
Open a browser and change the URL to http://localhost:3000/api/cities. You should see the list of cities in the browser.Let’s add an API to add a new city to the collection. It is going to be a POST API that checks for existence of the city by its name before adding the city. If the city is already present in the collection, it has to send an error to the client saying “City already exists”.
app.post('/api/cities', function(request, response){
var city = request.body;
console.log(city);
for(var index = 0; index < cities.length; index++){
if(cities[index].name === city.name){
response.status(409).send({error: "City already exists"});
return;
}
}
cities.push(city);
response.send(cities);
});
The statement inside the if condition sends error to the client with status 409. You can test it using Fiddler or, Postman. The following screenshot shows a request made to the above POST API in Fiddler:Similarly, we can define response to a PUT request using app.put method. Following API modifies entry of a city:
app.put('/api/cities/:name', function(request, response){
var city = request.body;
console.log(city);
for(var index = 0; index < cities.length; index++){
if(cities[index].name === request.params.name){
cities[index].country = city.country;
response.send(cities);
return;
}
}
response.status(404).send({error: 'City not found'});
});
This API can also be tested using Fiddler as we did for the POST API.Conclusion
It is very easy to get started with Node.js and build a few REST APIs using frameworks like express.js. We will see more examples and explore more features of Node.js and express.js in future posts. Stay tuned!Download the entire source code of this article (Github).
Using Node.js to build REST APIs
Reviewed by Unknown
on
11:36:00
Rating:
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Node JS Online Training from India . or learn thru Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Online Training
Thanks for sharing such kind of information.
ReplyDeleteFor Best Node.JS web application services must visit at 4 Square Logic IT Solutions .we are providing yoou best services within your budget.
The article is very informative. Thank you so much for sharing
ReplyDeleteNode JS Online training
Node JS training in Hyderabad