SkillAgentSearch skills...

Fbgraph

NodeJs module to access the facebook graph api

Install / Use

/learn @criso/Fbgraph
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Stay Classy, Facebook

FBgraph is a nodejs module that provides easy access to the facebook graph api

npm downloads

Oh nooooooesss - MOAR facebook

I created this because I wanted to access FB's graph from node. The libraries I found, felt clunky to me, and I needed an excuse to create a node module.

All calls will return json. Facebook sometimes (on friend requests, deleting test users, access token request) decides to just return a string or true or redirects directly to the image. I say nay-nay! Let's make it Disney, and keep things consistent!

Installation via npm

$ npm install fbgraph

var graph = require('fbgraph');

Authentication

If you get an accesstoken via some other Oauth module like everyauth , connect-auth or node-oauth you can just set the access token directly. Most get calls, and pretty much all post calls will require an access_token

Static access token (used on all calls)

    graph.setAccessToken(access_token);

To use a specific access token for a particular request

    // pass it in as part of the url
    graph.post(userId + "/feed?access_token=007", wallPost, function(err, res) {
        // returns the post id
        console.log(res); // { id: xxxxx}
    });

This is how you would get authenticated using only the fbgraph module. More details below on the express app section

    // get authorization url
    var authUrl = graph.getOauthUrl({
        "client_id":     conf.client_id
      , "redirect_uri":  conf.redirect_uri
    });

    // shows dialog
    res.redirect(authUrl);

    // after user click, auth `code` will be set
    // we'll send that and get the access token
    graph.authorize({
        "client_id":      conf.client_id
      , "redirect_uri":   conf.redirect_uri
      , "client_secret":  conf.client_secret
      , "code":           req.query.code
    }, function (err, facebookRes) {
      res.redirect('/loggedIn');
    });

Securing API calls

Facebook recommends adding the appsecret_proof parameter to all API calls to verify that the access tokens are coming from a valid app. You can make this happen automatically by calling graph.setAppSecret(app_secret), which will be used on all calls to generate the appsecret_proof hash that is sent to Facebook. Make sure you also set the access token for the user via graph.setAccessToken.

Extending access token expiration time

If you want to extend the expiration time of your short-living access token, you may use extendAccessToken method as it is shown below:

    // extending static access token
    graph.extendAccessToken({
        "client_id":      conf.client_id
      , "client_secret":  conf.client_secret
    }, function (err, facebookRes) {
       console.log(facebookRes);
    });

    // extending specific access token
    graph.extendAccessToken({
        "access_token":    client_access_token
      , "client_id":      conf.client_id
      , "client_secret":  conf.client_secret
    }, function (err, facebookRes) {
       console.log(facebookRes);
    });


How requests are made

All calls are made using the request nodejs module Why? something to do with wheels and re-invention.

Request options are directly mapped and can be set like so:

var options = {
    timeout:  3000
  , pool:     { maxSockets:  Infinity }
  , headers:  { connection:  "keep-alive" }
};

graph
  .setOptions(options)
  .get("zuck", function(err, res) {
    console.log(res); // { id: '4', name: 'Mark Zuckerberg'... }
  });

Possible options can be found on the request github page

followRedirect cannot be overriden and has a default value of false encoding will have utf-8 as default if nothing is set

Request Object

The request object is exposed as a property on graph object. So that all the request api can be accessed.

var graphObject = graph
  .get("zuck", function(err, res) {
    console.log(res); // { id: '4', name: 'Mark Zuckerberg'... }
  });

// abort the request.
graphObject.request.abort();

Pagination

Pagination in Facebook is done either with a cursor or a next url to call. To simplify the fbgraph API, it's possible to use a fully constructed URL in order to get the next page. See the following example:

// note: you might want to prevent the callback hell :)
graph.get('likes', {limit: 2, access_token: "foobar"}, function(err, res) {
  if(res.paging && res.paging.next) {
    graph.get(res.paging.next, function(err, res) {
      // page 2
    });
  }
});

Setting the version of the Graph Api

graph.setVersion("2.8");

See Facebook API changelog for available versions.

Read data from the Graph Api

graph.get("zuck", function(err, res) {
  console.log(res); // { id: '4', name: 'Mark Zuckerberg'... }
});

params in the url

graph.get("zuck?fields=picture", function(err, res) {
  console.log(res); // { picture: 'http://profile.ak.fbcdn.net/'... }
});

params as an object

var params = { fields: "picture" };

graph.get("zuck", params,  function(err, res) {
  console.log(res); // { picture: "http://profile.ak.fbcdn.net/..." }
});

GraphApi calls that redirect directly to an image will return a json response with relevant fields

graph.get("/zuck/picture", function(err, res) {
  console.log(res); // { image: true, location: "http://profile.ak.fb..." }
});

Search data from the Graph Api

Search for public posts that contain brogramming

var searchOptions = {
    q:     "brogramming"
  , type:  "post"
};

graph.search(searchOptions, function(err, res) {
  console.log(res); // {data: [{id: xxx, from: ...}, {id: xxx, from: ...}]}
});

Publish data to the Graph Api

All publish requests will require an access token

only needs to be set once

graph.setAccessToken(accessToken);

Post a message on the user's wall

var wallPost = {
  message: "I'm gonna come at you like a spider monkey, chip!"
};

graph.post("/feed", wallPost, function(err, res) {
  // returns the post id
  console.log(res); // { id: xxxxx}
});

Delete a Graph object

To delete a graph object, provide an object id and the response will return {data: true} or {data:false}

graph.del(postID, function(err, res) {
  console.log(res); // {data:true}/{data:false}
});

Performing a batch request

Batching allows you to pass instructions for several operations in a single HTTP request.

graph.batch([
  {
    method: "GET",
    relative_url: "me" // Get the current user's profile information
  },
  {
    method: "GET",
    relative_url: "me/friends?limit=50" // Get the first 50 friends of the current user
  }
], function(err, res) {
  console.log(res);
  // [
  //   {
  //     "code": 200, 
  //     "headers":[
  //       {"name": "Content-Type", "value": "text/javascript; charset=UTF-8"}
  //     ],
  //     "body": "{\"id\":\"…\"}"
  //   },
  //   {
  //     "code": 200,
  //     "headers":[
  //       {"name": "Content-Type", "value": "text/javascript; charset=UTF-8"}
  //     ],
  //     "body":"{\"data\": [{…}]}"
  //   }
  // ]
});

Performing a FQL query

A single FQL query is done by sending a query as a string

var query = "SELECT name FROM user WHERE uid = me()";

graph.fql(query, function(err, res) {
  console.log(res); // { data: [ { name: 'Ricky Bobby' } ] }
});

You can specify additional options by adding a JSON object

var query = "SELECT name FROM user WHERE uid = me()";
var options = {access_token: "foobar"};

graph.fql(query, options, function(err, res) {
  console.log(res); // { data: [ { name: 'Ricky Bobby' } ] }
});

Performing a FQL Multi-Query

FQL Multi-Queries are done by sending in an object containing the separate queries

var query = {
    name:         "SELECT name FROM user WHERE uid = me()"
  , permissions:  "SELECT email, user_about_me, user_birthday FROM permissions WHERE uid = me()"
};

graph.fql(query, function(err, res) {
  console.log(res);
  // { data: [
  //   { name: 'name', fql_result_set: [{name: 'Ricky Bobby'}] },
  //   { name: 'permissions', fql_result_set: [{email: 1, user_about_me: 1...}] }
  // ]}
});

Rockin' it on an Express App

This example assumes that you have a link on the main page / that points to /auth/facebook. The user will click this link and get into the facebook authorization flow ( if the user hasn't already connected) After authorizing the app the user will be redirected to /UserHasLoggedIn

npm install --save express fbgraph method-override body-parser errorhandler pug
/**
 * Module dependencies.
 */

var express   = require('express')
  , graph     = require('fbgraph');
var app = express(); 
var server = require("http").createServer(app);


// this should really be in a config file!
var conf = {
    client_id:      'APP-PUBLIC-ID'
  , client_secret:  'APP-SECRET-ID'
  , scope:          'email, user_about_me, user_birthday, user_location, publish_actions'
  // You have to set http://localhost:3000/ as your website
  // using Settings -> Add platform -> Website
  , redirect_uri:   'http://localhost:3000/auth'
};


// Configuration
var methodOverride = require('method-override');
var bodyParser = requ
View on GitHub
GitHub Stars1.1k
CategoryDevelopment
Updated1mo ago
Forks176

Languages

JavaScript

Security Score

80/100

Audited on Feb 23, 2026

No findings