Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Wednesday, November 7, 2012

Facebook API with Node.js

Facebook API is very powerful, it reveals a lot of data. Lets say that we want to work with the Facebook API from node.js to get some data from Facebook.

In this post I will explain how to achieve this task, I assume that you already have a valid access token of a Facebook user, If you didn't reach to this point, this link will show you how to start.

The module
The first thing is to build a module for Node, I want this module to be able to get a Facebook API open graph path (such as: /me/friends) and retrieve the data from Facebook. In this module I choose to work with the https module of node.js, with this module I can make secured requests to Facebook via https.

facebook.js
var https = require('https');

exports.get = function(accessToken, apiPath, callback) {
    // creating options object for the https request
    var options = {
        // the facebook open graph domain
        host: 'graph.facebook.com',

        // secured port, for https
        port: 443,

        // apiPath is the open graph api path
        path: apiPath + '?access_token=' + accessToken,

        // well.. you know...
        method: 'GET'
    };

    // create a buffer to hold the data received
    // from facebook
    var buffer = '';

    // initialize the get request
    var request = https.get(options, function(result){
        result.setEncoding('utf8');

        // each data event of the request receiving
        // chunk, this is where i`m collecting the chunks
        // and put them together into one buffer...
        result.on('data', function(chunk){
            buffer += chunk;
        });

        // all the data received, calling the callback
        // function with the data as a parameter
        result.on('end', function(){
            callback(buffer);
        });
    });
    
    // just in case of an error, prompting a message
    request.on('error', function(e){
        console.log('error from facebook.get(): '
                     + e.message);
    });

    request.end();
}

Now, In your Node.js server, include this facebook module and call the get() function with the open graph api path that you want.

var facebook = require('./facebook');
facebook.get('FB_ACCESS_TOKEN', '/me/friends', function(data){
    console.log(data);
});
The get() function is a generic function, you can call it with your api request path, pass the access token of the current user and a callback function to be called when the data is ready.