NodeJS RESTful Services.

Overview

You will learn how to develop http services using node.js.

Http Concepts

Http stands for HyperText Transfer Protocol.

Hypertext is generally defined as any block of content or text that includes hyperlinks to other documents, images, or multimedia content as shown in the example below:

<p>This html para is an example of hypertext. It is generally defined as any block of content or text that includes <a href=’wikipedia.com/hyperlinks">hyperlinks</a> to other <a href="wikipedia.com/documents">documents</a>, images, or multimedia content.</p>

HTTP is a protocol for sending and receiving hypertext.

It was Invented by Tim Berners Lee in 1989. First version of HTTP had only GET method that would request a html page from server.

Principles of Http Services

Http Methods/Operations

Sample Http Request

Sample Http Response

 

Http Content Types

Http Status Codes

Tools to View Http Requests

  1. fiddler, postman, curl

 

Project Setup

 

Try It Now

  1. Download and start Fiddler. Try the exercises in the video: https://www.youtube.com/watch?v=gujBKFGwjd4
  2. Download and run curl. Try the exercises in the tutorial: http://curl.haxx.se/docs/httpscripting.html

 

Simple Tutorial

In this tutorial, we will build a simple http server that will echo back the incoming request. You can see the full code for this tutorial in Tutorial.js file of the project git repo

First, import the required http, queryparser modules.

var http = require('http');

var querystring = require('querystring');

var PORT = 3000;

 

Next, create an instance of the http server and make it listen on port 3000.

var PORT = 3000;

var server = http.createServer(handleRequest);

function handleRequest(request, response){

                response.end(“Hello World”);

}

 

function handleRequest(request, response){

    response.end(“Hello World”);

}

server.listen(PORT, function(){

     console.log("server listening on port " + PORT);

});

 

 

You can run the above code by doing node tutorial.js. The http server will listen on port 3000 and the handleRequest function will be called when any incoming request is returned. For now, the handleRequest method simply returns ‘Hello World”.

Now, lets expand handleRequest to echo back the incoming request details (such as method type, url and request body). For this, we’ve to add event listeners for the request “data” and “end” events as described here.

We implement a listener for ‘data’ event where we add the latest message chunk received to a string buffer. When the ‘end’ event is received, the bodyStr variable will have the full content of the incoming http request.

 

function handleRequest(request, response){

   var bodyStr = "";

   request.on('data',function(chunk);

   console.log("recvd " + chunk.toString());

    bodyStr += chunk.toString();

 });

 request.on('end', function() {

  var str = "Received " + request.method + " request for " + request.url + " body: " + bodyStr;

  console.log(str);

  response.end(JSON.stringify(str));

 });

}

 

You can look at the final code in Tutorial.js. You can also run the basic tests by running jasmine-node spec\tests\TutorialSpec.js

Project Activities

 

CalculatorHttpService

In this activity, you will implement a http service that supports the following operations:

  1. GET /calculator?op=<operation>&op1=<num>&op2=<num> should return the operation result on the numbers in the response.
  2. POST /calculator and request body is a json object {"op":<operation>,"op1":<num>,"op2":<num>} and returns the operation result on the numbers in the response.
Supported Operations:add,sub,mul,div.You will write your code into CalculatorHttpService.js.

ContactsHttpService

In this activity, you will implement a REST service to manage contacts. The rest service will store/retrieve contacts in a mysql database. The rest service will implement the following operations:

  1. GET /contacts/id –This will read the specified contact from in memory data structure and return it in the response.
  2. POST /contacts – This will accept a JSON payload, create the contact in memory data structure and return id in the JSON response. Format of JSON request body is: {"firstName":"","lastName":"","phone":""} and response format is {"id":<id of the new contact>}
  3. PUT /contacts/id – This will update the specified contact's details with the details in the JSON payload. Only fields that are specified in the request body need to be updated. Other fields of that contact should remain unchanged. Format of JSON request body is: {"firstName":"","lastName":"","phone":""} and response format is {"id":<id of the new contact>}

You will write your code into ContactsHttpService.js