Call REST API with node.js

Node.js is really cool. Based on Google V8 JavaScript engine allows to write the server side in JavaScript. The great benefits on that are: you can manipulate natively JSON, write in the same language UI and back-end and think asynchronously natively. In my previous articles I’ve shown how to manage WebSockets and UDP to pull live data to the web but how to integrate REST API services in the server side?
The simple way is to use http/https node.js library (http://nodejs.org/api/https.html).
Because I took an hour to understand how to use it for doing REST calls (GET and POST) I want to share the code within the community.

var https = require('https');

/**
 * HOW TO Make an HTTP Call - GET
 */
// options for GET
var optionsget = {
	host : 'graph.facebook.com', // here only the domain name
	// (no http/https !)
	port : 443,
	path : '/youscada', // the rest of the url with parameters if needed
	method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsget, function(res) {
	console.log("statusCode: ", res.statusCode);
	// uncomment it for header details
//	console.log("headers: ", res.headers);


	res.on('data', function(d) {
		console.info('GET result:\n');
		process.stdout.write(d);
		console.info('\n\nCall completed');
	});

});

reqGet.end();
reqGet.on('error', function(e) {
	console.error(e);
});

/**
 * HOW TO Make an HTTP Call - POST
 */
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
	"message" : "The web of things is approaching, let do some tests to be ready!",
	"name" : "Test message posted with node.js",
	"caption" : "Some tests with node.js",
	"link" : "http://www.youscada.com",
	"description" : "this is a description",
	"picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
	"actions" : [ {
		"name" : "youSCADA",
		"link" : "http://www.youscada.com"
	} ]
});

// prepare the header
var postheaders = {
	'Content-Type' : 'application/json',
	'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
	host : 'graph.facebook.com',
	port : 443,
	path : '/youscada/feed?access_token=your_api_key',
	method : 'POST',
	headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = https.request(optionspost, function(res) {
	console.log("statusCode: ", res.statusCode);
	// uncomment it for header details
//	console.log("headers: ", res.headers);

	res.on('data', function(d) {
		console.info('POST result:\n');
		process.stdout.write(d);
		console.info('\n\nPOST completed');
	});
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
	console.error(e);
});

/**
 * Get Message - GET
 */
// options for GET
var optionsgetmsg = {
	host : 'graph.facebook.com', // here only the domain name
	// (no http/https !)
	port : 443,
	path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed
	method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsgetmsg);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsgetmsg, function(res) {
	console.log("statusCode: ", res.statusCode);
	// uncomment it for header details
//	console.log("headers: ", res.headers);


	res.on('data', function(d) {
		console.info('GET result after POST:\n');
		process.stdout.write(d);
		console.info('\n\nCall completed');
	});

});

reqGet.end();
reqGet.on('error', function(e) {
	console.error(e);
});

To run it just copy and save to a file (call.js for example), change your_api_key with yours and execute it (may be you have to authorize the application to POST data to facebook page (this out of scope of this demo).

node call.js

You can change the url of your options to call other REST APIs.

Write a comment if you need help!

13 thoughts on “Call REST API with node.js

  1. Nice work but when you’re receiving the response from the remote API, you should also test the end and error events because you’re not sure that the data event contains all the response (it may not if the API response is too long, if so, you have to accumulate within a variable on data event and use it on end event).

  2. Yes, agreed, I did that with a little help from underscore.js by adding the following:

    exports.poller = function () {
        var reqGet = https.request(fourSquareGet, function (res) {
            var content;
    
            res.on('data', function (chunk) {
                content += chunk;
            });
            res.on('end', function () {
                _.each(content.response.venues, function (value, key) {
                    if (value.hereNow.count > 0) {
                        // Always delete the old collection
                        db.checkins.remove({});
                        db.checkins.save(content.response.venues, function (err, saved) {
                            if (err || !saved) throw err;
                        });
                    }
                });
                console.info("Successfully saved from Foursquare\n");
            });
        });
    
        reqGet.end();
        reqGet.on('error', function (e) {
            console.error(e);
        });
    };
    

    Thanks for providing this!

  3. Thanks Loutilities for this example of adding reqGet.on(‘error’,… and res.on(‘end’, function ()…
    This complete the example 🙂

  4. Hi Giulioro, your post was helpful thanks. It seems there must be some libraries available for making REST calls even simpler. Let us know if you are using anything higher level.

    • Hi that’s true. The example is at low level. It will follow a post about that
      Thanks for the comment
      Giulio

  5. Pingback: Calling Remote Rest API from Node.js

  6. hi giulioroggero,
    Thanks for this post, I have some question about the response that I get back. what exactly its trying to print on console if I have removed all the sections that deal with the information after the call returns. please could you specify.

    below is the code that I tried and I got the following response

    code snippet:

    var https = require(‘https’);
     
    /**
     * HOW TO Make an HTTP Call – GET
     */
    // options for GET
    var optionsget = {
        host : ‘graph.facebook.com’, // here only the domain name
        // (no http/https !)
        port : 443,
        path : ‘/youscada’, // the rest of the url with parameters if needed
        method : ‘GET’ // do GET
    };
     
    console.info(‘Options prepared:’);
    //console.info(optionsget);
    console.info(‘Do the GET call’);
     
    // do the GET request
    var reqGet = https.request(optionsget, function(res) {
        console.log(“statusCode: “, res.statusCode);
        // uncomment it for header details
    //  console.log(“headers: “, res.headers);
     
     
        res.on(‘data’, function(d) {
            console.info(‘GET result:\n’);
          //  process.stdout.write(d);
            console.info(‘\n\nCall completed’);
        });
     
    });
     
    reqGet.end();
    reqGet.on(‘error’, function(e) {
       // console.error(e);
    });
     
    // Response.

    { domain: null,
    _events:
    { response: { [Function: g] listener: [Function] },
    socket: { [Function: g] listener: [Function] },
    error: [Function] },
    _maxListeners: 10,
    output: [ ‘GET /youscada HTTP/1.1\r\nHost: graph.facebook.com\r\nConnection: keep-alive\r\n\r\n’ ],
    outputEncodings: [ undefined ],
    writable: true,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: true,
    useChunkedEncodingByDefault: false,
    sendDate: false,
    _headerSent: true,
    _header: ‘GET /youscada HTTP/1.1\r\nHost: graph.facebook.com\r\nConnection: keep-alive\r\n\r\n’,
    _hasBody: true,
    _trailer: ”,
    finished: true,
    _hangupClose: false,
    socket: null,
    connection: null,
    agent:
    { domain: null,
    _events: { free: [Function] },
    _maxListeners: 10,
    options: {},
    requests: {},
    sockets: { ‘graph.facebook.com:443’: [Object] },
    maxSockets: 5,
    createConnection: [Function: createConnection] },
    socketPath: undefined,
    method: ‘GET’,
    path: ‘/youscada’,
    _headers: { host: ‘graph.facebook.com’ },
    _headerNames: { host: ‘Host’ } }

  7. Hi ravi, I tried your code but I don’t have any output on console like yours. May be there is one of your node module in debug mode or something similar?

    Here is the test.

    var https = require('https');
    /**
     * HOW TO Make an HTTP Call – GET
     */
    // options for GET
    var optionsget = {
        host : 'graph.facebook.com', // here only the domain name
        // (no http/https !)
        port : 443,
        path : '/youscada', // the rest of the url with parameters if needed
        method : 'GET' // do GET
    };
     
    console.info('Options prepared:');
    //console.info(optionsget);
    console.info('Do the GET call');
     
    // do the GET request
    var reqGet = https.request(optionsget, function(res) {
        console.log('statusCode: ', res.statusCode);
        // uncomment it for header details
        //  console.log('headers: ', res.headers);
     
     
        res.on('data', function(d) {
            console.info('GET result:\n');
            //process.stdout.write(d);
            console.info('\n\nCall completed');
        });
     
    });
     
    reqGet.end();
    reqGet.on('error', function(e) {
       // console.error(e);
    });
    

    Running it I obtain the folllowing

    isolanet:tmp roggero$ node test.js 
    Options prepared:
    Do the GET call
    statusCode:  200
    GET result:
    
    
    
    Call completed
    
  8. que modulos existen actualmente para poder consumir servicios rest con node.js????mira lo q yo kiero hacer es consumir un servicio web q fue creado en asp …. lo kiero consumir desde node.js y luego kiero enviar ese servicio a los usuarios o clientes crees q se pueda hacer eso??????? xfas necesito ayuda …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s