Using Node.js to build REST APIs

Posted by: Ravi Kiran , on 6/25/2015, in Category Node.js
Views: 32307
Abstract: Building basic REST APIs using Node.js. We will build a simple set of REST APIs to perform GET, POST and PUT operations.

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.

 

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.

In general, RESTful services are defined based on HTTP protocol and they use the HTTP verbs (GET, PUT, POST and DELETE) as the interface. So, they work exactly the same way as the web works.

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 express

We 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:

nodejs-post-request

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)

Read the next article in this series Node.js Modules System

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook