The Facebook Graph API Part 1

I’ve had a few requests for a tutorial on using the facebook graph api with my social plugin, so here it is!

My Social Unity Plugin for Android supports the Facebook Graph API. So what does that mean exactly? Well facebook expose their functionality via a rather cool but perhaps slightly confusing web interface. This interface is driven by HTTP requests and the data you get back is in the JSON format. Quickly check those links so you know what both of these are then come back here…

The Graph API is well documented and you can easily test a query by using the Graph API Explorer. So if I said you can get the current user’s profile by using a graph path of ‘me’, you can easily check this by going to the Graph API Explorer and doing this:

In my plugin you can do the same thing on the demo screen:

Or in code:

FacebookUnityPlugin.GenericRequest("me","","GET","");

In all the above cases, the response you would get will be in JSON, similar to:

{
  "id": "1234565", 
  "name": "Fred Bloggs", 
  "first_name": "Fred", 
  "last_name": "Bloggs", 
  "location": {
    "id": "111112222", 
    "name": "London, United Kingdom"
  }, 
  "gender": "male", 
  "timezone": 0, 
  "locale": "en_GB", 
  "verified": true, 
  "updated_time": "2012-07-24T09:52:15+0000"
}

So how do we extract all that information out in C# within Unity? Well the latest version of my plugin includes ‘LitJSON‘ which is remarkably good at doing this, for example if the above JSON was in a string variable ‘response’, you could get the user’s last name by:

JsonData jdata = JsonMapper.ToObject(response);
lastname = (string)jdata["last_name"];

Nice and simple! In my plugin, all responses from a GenericRequest come back via the gameobject ‘UnityGameObjectReceiver’, and you need a script attached to this gameobject that has a ‘OnRequestResponse’ method (see the demo for an example).

Part Two of this tutorial will cover more complex queries…