facebook
Facebook Open Graph API: Showing List Of Friends
November 29, 2010
3

This guide assumes familiarity with setting up application susing Facebook Open Graph API in JavaScript, which is explained here:
/blog/2010/11/facebook-open-graph-api-authenticating-in-iframe-applications/

Simple List

To get the list of friends using Open Graph API, you can call:

FB.api('/me/friends', callbackFunction);

after the user is authenticated. Example:

function onFriendsListLoaded(response)
{
var divTarget=document.getElementById("friends-list-container");
var data=response.data;
//alert("divTarget="+divTarget+"ndata="+data);
for (var friendIndex=0; friendIndex<data.length; friendIndex++)
{
  var divContainer = document.createElement("div");
  divContainer.innerHTML="<b>" + data[friendIndex].name + "</b>";
  divTarget.appendChild(divContainer);
}
}

function showFriendsList()
{
  FB.api('/me/friends', onFriendsListLoaded);
}

Note:

  • FB.api(‘/me/friends’, onFriendsListLoaded) sends the request to Facebook and onFriendsListLoaded is the callback function.
  • The data is returned in the response object, which contains array of friends. Each friend object has name field and id field.
  • friends-list container is a div that will hold the list of friends. You can add scrollbar and style the div if you want.
  • The test page is here: /tutorial/facebook-graph-api-friens-selector/simple.html

List With Picture

To get the profile picture of the friend, you can use this URL:

https://graph.facebook.com/friendId/picture

where friendId is the id of your friend. The good news is, we already have the ID from the call above, so all we need is to enclose the picture within an tag. The example below only displays the list, but you can extend it to create a list of selectable friends (I will write a tutorial on this later).

Example:

function onFriendsListLoaded(response)
{
  var divTarget=document.getElementById("friends-list-container");
  var data=response.data;
  //alert("divTarget="+divTarget+"ndata="+data);
  for (var friendIndex=0; friendIndex<data.length; friendIndex++)
  {
    var divContainer = document.createElement("div");
    divContainer.innerHTML="<hr><img src='http://graph.facebook.com/"+data[friendIndex].id+"/picture'></img>"+
"<br>"+data[friendIndex].name;
    divTarget.appendChild(divContainer);
  }
}

function showFriendsList()
{
  FB.api('/me/friends', onFriendsListLoaded);
}

This will show each user’s picture above the user name, such as below:
.
The formatting is very plain here but this is intentional so that you can format it any way you want.

The example is here: /tutorial/facebook-graph-api-friens-selector/with-picture.html

Make sure you are testing with an account that has friends, otherwise nothing will be shown.

Another example with randomized order and only displaying limited number of friends (in this example, 5 friends):
http://www.permadi.com/tutorial/facebook-graph-api-friens-selector/with-picture-limit.html