Friday, February 7, 2014

Restful web services in node.js

In my latest blog restful web services with jetty and jersey I was trying to create rest web services simple as node.js, so I decide to show you how simple is to write this services with node.js.

First you will need node installed, you can install it from here nodejs.org, I'm going to use the express framework (expressjs.com) for node to help me develop the services, so to install express just go to the folder in which your projects will reside and with the help of the npm (node packaged modules) type the following command:

                 [jluna@host projects]$ npm install express

With this the express framework will be installed locally at your projects folder, now you can start creating the restful web services, first create a file in the projects folder for example services.js.

To use express use the following:

var express = require('express');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
view raw gistfile1.js hosted with ❤ by GitHub

Once imported express to create a service just use one of its methods like this:

app.get('PATH', function(req, res) {
.........
});
view raw gistfile1.js hosted with ❤ by GitHub
Finally, just configure the port and listen:

                 app.listen(process.env.PORT || 9999);

So here it is the whole script that contains the services:

var express = require('express');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/employee/getEmployee/:name', function(req, res) {
res.type('application/json');
var name = req.params.name;
console.log("Parameter: " + name);
employee = new Object();
employee.name = name;
employee.age = 25;
employee.deparment = "HR";
employee.wage = 15000.00;
address = new Object();
address.city = "Massachusetts";
address.state = "Springfield";
address.street = "Evergreen";
address.zip = 66450;
employee.address = address;
res.json(employee);
});
app.post('/employee/postEmployee', function(req, res) {
var employee = req.body;
console.log("Got request: " + JSON.stringify(employee));
res.send(employee);
});
app.listen(process.env.PORT || 9999);
view raw gistfile1.js hosted with ❤ by GitHub


As you can see the first service receives a parameter, this is specified in the path '/employee/getEmployee/:name', and to obtain the value of the parameter just get it from the request:

                  var name = req.params.name;

In javascript to create objects you don't have to define a class like in java just specify its properties when the object is created:

                 employee = new Object();
                 employee.name = name;
                 employee.age = 25;
                 employee.deparment = "HR";
                 employee.wage = 15000.00;

This has its benefits and its risks but I won't get into there, also there are other ways in javascript to create objects, you can define a function.

Finally to send the response to the client the json() method is used to parse the objects to json:

                 res.json(employee);

In the post method the interesting thing to see is that it is receiving an object, to access this object just get it from the body

                 var employee = req.body;

And then you can access the object like this:

                 console.log("Got name: " + employee.name);

Well to run the script just use the following  command in the path where the script is:

                 [jluna@host projects]$ node services.js

And the script should be up and running.

To test the script you can use the following commands:

curl -i -X GET -H 'Content-Type: application/json'  http://localhost:9999/employee/getEmployee/James

curl -i -X POST -H 'Content-Type: application/json'  -d '{"address": {"city": "Massachusetts","state": "Springfield","street": "Evergreen","zip": "66450"},"age": "25","deparment": "HR","name": "James","salary": "0.0"}'  http://localhost:9999/employee/postEmployee

In the console you should see the output, also here it is a java client you can use:

package node.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import dto.Employee;
public class RestClient {
public static void main(String [] args){
Client client = Client.create();
//GET
WebResource webResource = client.resource("http://localhost:9999/employee/getEmployee/James");
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
Employee output = response.getEntity(Employee.class);
System.out.println("Output json client GET....");
System.out.println(output);
//POST
webResource = client.resource("http://localhost:9999/employee/postEmployee");
response = webResource.accept("application/json").type("application/json").post(ClientResponse.class, output);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output json client POST ....");
System.out.println(response.getEntity(String.class));
}
}
view raw gistfile1.java hosted with ❤ by GitHub

As you can see is very simple to create the services in node.js.