Facebook: Accessing Graph API

Exclusive offer: get 50% off this eBook here
Facebook Graph API Development with Flash

Facebook Graph API Development with Flash — Save 50%

Build social Flash applications fully integrated with the Facebook Graph API

$26.99    $13.50
by Michael James Williams | January 2011 | Beginner's Guides

Facebook has a huge store of information, on people, companies, events, photo albums, and more. It also knows how all of these are linked: which person owns each album; which people appear in each photo; which company is organizing each event.

For four years, this was accessed using a huge, sprawling API, which got more complex as new abilities were bolted on to it. In April 2010, Facebook launched the Graph API, greatly simplifying how developers can retrieve all of this data.

In this article by Michael James Williams, author of Facebook Graph API Development with Flash Beginner's Guide, we shall:

  • Explore the Facebook Graph
  • Learn what the Graph API is, and how it structures all the data on Facebook
  • Access public Graph data using AS3 and the Graph API

 

Facebook Graph API Development with Flash

Facebook Graph API Development with Flash

Build social Flash applications fully integrated with the Facebook Graph API

  • Build your own interactive applications and games that integrate with Facebook
  • Add social features to your AS3 projects without having to build a new social network from scratch
  • Learn how to retrieve information from Facebook's database
  • A hands-on guide with step-by-step instructions and clear explanation that encourages experimentation and play
        Read more about this book      

(For more resources on Facebook, see here.)

Accessing the Graph API through a Browser

We'll dive right in by taking a look at how the Graph API represents the information from a public Page.

When I talk about a Page with a capital P, I don't just mean any web page within the Facebook site; I'm referring to a specific type of page, also known as a public profile. Every Facebook user has their own personal profile; you can see yours by logging in to Facebook and clicking on the "Profile" link in the navigation bar at the top of the site. Public profiles look similar, but are designed to be used by businesses, bands, products, organizations, and public figures, as a way of having a presence on Facebook.
This means that many people have both a personal profile and a public profile. For example, Mark Zuckerberg, the CEO of Facebook, has a personal profile at http://www.facebook.com/zuck and a public profile (a Page) at http://www.facebook.com/markzuckerberg. This way, he can use his personal profile to keep in touch with his friends and family, while using his public profile to connect with his fans and supporters.
There is a second type of Page: a Community Page. Again, these look very similar to personal profiles; the difference is that these are based on topics, experience, and causes, rather than entities. Also, they automatically retrieve information about the topic from Wikipedia, where relevant, and contain a live feed of wall posts talking about the topic.
All this can feel a little confusing – don't worry about it! Once you start using it, it all makes sense.

Time for action – loading a Page

Browse to http://www.facebook.com/PacktPub to load Packt Publishing's Facebook Page. You'll see a list of recent wall posts, an Info tab, some photo albums (mostly containing book covers), a profile picture, and a list of fans and links.

Facebook: Accessing Graph API

That's how website users view the information. How will our code "see" it? Take a look at how the Graph API represents Packt Publishing's Page by pointing your web browser at https://graph.facebook.com/PacktPub. This is called a Graph URL – note that it's the same URL as the Page itself, but with a secure https connection, and using the graph sub domain, rather than www.

What you'll see is as follows:

{
"id": "204603129458",
"name": "Packt Publishing",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/
hs302.ash1/23274_204603129458_7460_s.jpg",
"link": "http://www.facebook.com/PacktPub",
"category": "Products_other",
"username": "PacktPub",
"company_overview": "Packt is a modern, IT focused book publisher,
specializing in producing cutting-edge books for communities of
developers, administrators, and newbies alike.\n\nPackt
published its first book, Mastering phpMyAdmin for MySQL
Management in April 2004.",
"fan_count": 412
}

What just happened?

You just fetched the Graph API's representation of the Packt Publishing Page in your browser.

The Graph API is designed to be easy to pick up – practically self-documenting – and you can see that it's a success in that respect. It's pretty clear that the previous data is a list of fields and their values.

The one field that's perhaps not clear is id; this number is what Facebook uses internally to refer to the Page. This means Pages can have two IDs: the numeric one assigned automatically by Facebook, and an alphanumeric one chosen by the Page's owner. The two IDs are equivalent: if you browse to https://graph.facebook.com/204603129458, you'll see exactly the same data as if you browse to https://graph.facebook.com/PacktPub.

Have a go hero – exploring other objects

Of course, the Packt Publishing Page is not the only Page you can explore with the Graph API in your browser. Find some other Pages through the Facebook website in your browser, then, using the https://graph.facebook.com/id format, take a look at their Graph API representations. Do they have more information, or less?

Next, move on to other types of Facebook objects: personal profiles, events, groups. For personal profiles, the id may be alphanumeric (if the person has signed up for a custom Facebook Username at http://www.facebook.com/username/), but in general the id will be numeric, and auto-assigned by Facebook when the user signed up.

For certain types of objects (like photo albums), the value of id will not be obvious from the URL within the Facebook website.

In some cases, you'll get an error message, like:

{
"error": {
"type": "OAuthAccessTokenException",
"message": "An access token is required to request
this resource."
}
}

Accessing the Graph API through AS3

Now that you've got an idea of how easy it is to access and read Facebook data in a browser, we'll see how to fetch it in AS3.

Time for action – retrieving a Page's information in AS3

Set up the project. Check that the project compiles with no errors (there may be a few warnings, depending on your IDE). You should see a 640 x 480 px SWF, all white, with just three buttons in the top-left corner: Zoom In, Zoom Out, and Reset View:

Facebook: Accessing Graph API

This project is the basis for a Rich Internet Application (RIA) that will be able to explore all of the information on Facebook using the Graph API. All the code for the UI is in place, just waiting for some Graph data to render. Our job is to write code to retrieve the data and pass it on to the renderers.

I'm not going to break down the entire project and explain what every class does. What you need to know at the moment is a single instance of the controllers. CustomGraphContainerController class is created when the project is initialized, and it is responsible for directing the flow of data to and from Facebook. It inherits some useful methods for this purpose from the controllers.GCController class; we'll make use of these later on.

Open the CustomGraphContainerController class in your IDE. It can be found in \src\controllers\CustomGraphContainerController.as, and should look like the listing below:

package controllers
{
import ui.GraphControlContainer;

public class CustomGraphContainerController extends GCController
{
public function CustomGraphContainerController
(a_graphControlContainer:GraphControlContainer)
{
super(a_graphControlContainer);
}
}
}

The first thing we'll do is grab the Graph API's representation of Packt Publishing's Page via a Graph URL, like we did using the web browser. For this we can use a URLLoader.

The URLLoader and URLRequest classes are used together to download data from a URL. The data can be text, binary data, or URL-encoded variables. The download is triggered by passing a URLRequest object, whose url property contains the requested URL, to the load() method of a URLLoader. Once the required data has finished downloading, the URLLoader dispatches a COMPLETE event. The data can then be retrieved from its data property.

Modify CustomGraphContainerController.as like so (the highlighted lines are new):

package controllers
{
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import ui.GraphControlContainer;

public class CustomGraphContainerController extends GCController
{
public function CustomGraphContainerController
(a_graphControlContainer:GraphControlContainer)
{
super(a_graphControlContainer);

var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
//Specify which Graph URL to load
request.url = "https://graph.facebook.com/PacktPub";
loader.addEventListener(Event.COMPLETE,
onGraphDataLoadComplete);
//Start the actual loading process
loader.load(request);
}

private function onGraphDataLoadComplete(a_event:Event):void
{
var loader:URLLoader = a_event.target as URLLoader;
//obtain whatever data was loaded, and trace it
var graphData:String = loader.data;
trace(graphData);
}
}
}

All we're doing here is downloading whatever information is at https://graph.facebook.com/PackPub and tracing it to the output window.

Test your project, and take a look at your output window. You should see the following data:

{"id":"204603129458","name":"Packt Publishing","picture":"http:\/\/
profile.ak.fbcdn.net\/hprofile-ak-snc4\/hs302.
ash1\/23274_204603129458_7460_s.jpg","link":"http:\/\/www.facebook.
com\/PacktPub","category":"Products_other","username":"PacktPub",
"company_overview":"Packt is a modern, IT focused book publisher,
specializing in producing cutting-edge books for communities of
developers, administrators, and newbies alike.\n\nPackt published
its first book, Mastering phpMyAdmin for MySQL Management in April
2004.","fan_count":412}

If you get an error, check that your code matches the previously mentioned code. If you see nothing in your output window, make sure that you are connected to the Internet. If you still don't see anything, it's possible that your security settings prevent you from accessing the Internet via Flash, so check those.

 

Facebook Graph API Development with Flash Build social Flash applications fully integrated with the Facebook Graph API
Published: December 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Facebook, see here.)

What just happened?

The line breaks and tabulation between values have been lost, and some characters have been escaped, making it hard to read… but you can see that this is the same data as we obtained when browsing to https://graph.facebook.com/PacktPub. No surprise here; that's all the URLLoader does.

The data's not very useful to us in that form. In order to do something with it, we need to convert it to an object that we can interact with natively in AS3.

The format which Graph API uses is called JSON (JavaScript Object Notation; pronounced "Jason").

JSON is a human-readable, text-based data format standard. It allows you to represent objects as key-value pairs, like so:

{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

The values can be strings (enclosed in quote marks), or numbers, Boolean values, or null (not enclosed in quote marks).

JSON objects can also contain arrays, using square brackets:

{
"key1": "value1",
"array":
[
"First item in array",
"Second item in array",
"Third item in array"
]
}

They can even contain other JSON objects, by nesting curly braces:

{
"key1": "value1",
"subObject":
{
"subKey1": "subValue1",
"subKey2": "subValue2",
}
}

These sub-objects can contain other objects and arrays, and arrays can contain other objects or arrays, too.

Note that this is very similar to the AS3 syntax for declaring an object:

var as3Object:Object = {
key1:"value1",
key2:"value2",
subObject:{
subKey1:"subValue1"
},
myArray:[1, 2, 3]
}

For more information, check out http://www.json.org.

Unlike with XML, AS3 has no native features for handling JSON objects – but there is an officially supported library that does.

Time for action – deserializing a JSON object

Adobe's as3corelib library contains a set of utility classes for serializing and deserializing JSON. It's available at http://github.com/mikechambers/as3corelib, but you don't need to download it, as it is already included in the \src\ directory of the project. (It consists of every class in com.adobe.*)

  1. In CustomGraphContainerController.as, import the JSON class:

    import com.adobe.serialization.json.JSON;

  2. Modify the onGraphDataLoadComplete() function so that it deserializes the JSON string to an object, instead of simply tracing the string:

    private function onGraphDataLoadComplete(a_event:Event):void
    {
    var loader:URLLoader = a_event.target as URLLoader;
    //obtain whatever data was loaded, and trace it
    var graphData:String = loader.data;
    var decodedJSON:Object = JSON.decode(graphData);
    }

  3. Trace the name property of this new object, to check that it worked:

    private function onGraphDataLoadComplete(a_event:Event):void
    {
    var loader:URLLoader = a_event.target as URLLoader;
    //obtain whatever data was loaded, and trace it
    var graphData:String = loader.data;
    var deserialisedJSON:Object = JSON.decode(graphData);
    trace("name:", decodedJSON.name);
    }

  4. Compile and run the SWF. Resulting output:

    name: Packt Publishing

What just happened?

We passed this string to the JSON.decode() method:

{
"id": "204603129458",
"name": "Packt Publishing",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/
hs302.ash1/23274_204603129458_7460_s.jpg",
"link": "http://www.facebook.com/PacktPub",
"category": "Products_other",
"username": "PacktPub",
"company_overview": "Packt is a modern, IT focused book
publisher, specializing in producing cutting-edge books for
communities of developers, administrators, and newbies
alike.\n\nPackt published its first book, Mastering
phpMyAdmin for MySQL Management in April 2004.",
"fan_count": 412
}

and it turned the string into a native AS3 object, as if we had typed this:

var graphObject:Object = {};
graphObject.id = "204603129458";
graphObject.name = "Packt Publishing";
graphObject.picture = "http://profile.ak.fbcdn.net/hprofile-aksnc4/
hs302.ash1/23274_204603129458_7460_s.jpg";
graphObject.link = "http://www.facebook.com/PacktPub";
graphObject.category = "Products_other";
graphObject.username = "PacktPub";
graphObject.company_overview = "Packt is a modern, IT focused
book publisher, specializing in producing cutting-edge books for
communities of developers, administrators, and newbies alike.\n\
nPackt published its first book, Mastering phpMyAdmin for MySQL
Management in April 2004."
graphObject.fan_count = 412;

(Note that unlike the raw string we had earlier, the slashes in the URLs have not been escaped.)

This means we can easily access any of the information Facebook has about this Page, or even iterate through every piece of data.

Time for action – visualizing the info

Enough traces! It's time we displayed something in our actual SWF.

CustomGraphContainerController inherits a method called renderGraphObject() which will take care of this for us. All we have to do is pass it an argument of type graph.GraphObject.

GraphObject.as is a simple class; feel free to open it and take a look:

package graph
{
import graph.controls.GraphObjectRenderer;
public dynamic class GraphObject extends BaseGraphItem
{
public var rendererObject:GraphObjectRenderer;
public var graphObjectListRenderers:Array = [];

public function GraphObject()
{

}
}
}

Honestly, there's no need to worry about any of the code there. All you need to know is that it's dynamic, which means that we can assign new properties to it during runtime, without having to specify their names beforehand. So we can do this:

var graphObject:GraphObject = new GraphObject();
graphObject.favoriteColor = "red";

When a GraphObject is passed to the CustomGraphContainerController.renderGraphObject() method, every single property of the GraphObject will be rendered in a fancy list, automatically. Every single property apart from the two that are defined in the class already, that is!

So what we have to do, inside CustomGraphContainerController.onGraphDataLoadComplete(), is:

  1. Create a new instance of GraphObject.
  2. Copy all the properties of decodedJSON to this new GraphObject.
  3. Pass the GraphObject to renderGraphObject().
  4. The code for doing that is as follows:

    private function onGraphDataLoadComplete(a_event:Event):void
    {
    var loader:URLLoader = a_event.target as URLLoader;
    //obtain whatever data was loaded, and trace it
    var graphData:String = loader.data;
    var decodedJSON:Object = JSON.decode(graphData);

    var graphObject:GraphObject = new GraphObject();
    //copy all the properties from decodedJSON to graphObject
    for (var key:String in decodedJSON)
    {
    graphObject[key] = decodedJSON[key];
    }
    this.renderGraphObject(graphObject);
    }

  5. Compile and test. The SWF is shown in the next screenshot:

Facebook: Accessing Graph API

You can click the Zoom In button a few times to make the Renderer larger and clearer, as in the screenshot above. Your Renderer might display the fields in a different order than depicted; Facebook returns the fields in an arbitrary order.

What just happened?

The window that appeared on stage is what I call a Renderer – specifically, a Graph Object Renderer. It can be dragged around by the title bar, the contents can be scrolled, and you can close it by clicking the button in the top-right corner.

So, you've successfully fetched data from Facebook's Graph API and displayed it in a SWF. Your SWF is flexible; change request.url to point to the Graph URL of a different Facebook object and you'll see it displayed in the Renderer.

Most of the data from the GraphObject is displayed in a text area inside the window, in a simple "key: value" format. The Page's name field is displayed in the window's title bar, and if the Page has a picture field (we can see from the JSON that PacktPub does), the image is downloaded and displayed inside the renderer using a Loader.

Like URLLoader, the flash.display.Loader class downloads the object that a given URLRequest points to, dispatching a COMPLETE event when ready. Unlike URLLoader, Loader is used to download images and SWFs, and the event is actually dispatched by one of its sub-objects, contentLoaderInfo. Also, Loader extends DisplayObject, and takes the appearance of the image when it has finished downloading. Flash's security model prevents an image's data being accessed by SWFs residing on a different domain than the image itself, unless there is a crossdomain policy file on the domain of the image that allows it. Fortunately, Facebook's cross-domain policy file is lenient, allowing such access by every domain.

So, really, this is just a graphical way of representing a Page object from the Graph API.

Summary

We learned a lot in this article about the Graph API: not just what it is, but also how to access it in AS3. We also discussed how the Graph API is so flexible, because it uses the same basic structure for every type of object in Facebook's database.


Further resources on this subject:


Facebook Graph API Development with Flash Build social Flash applications fully integrated with the Facebook Graph API
Published: December 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Michael James Williams

Michael James Williams is a freelance Flash developer and technical concept writer. He is the technical editor for Activetuts+, and writes AS3 game development tutorials on his blog. You can find him on Twitter, too: @MichaelJW.

Books From Packt


Facebook Graph API Development with Flash
Facebook Graph API Development with Flash

Flash 10 Multiplayer Game Essentials
Flash 10 Multiplayer Game Essentials

SketchUp 7.1 for Architectural Visualization: Beginner's Guide
SketchUp 7.1 for Architectural Visualization: Beginner's Guide

Kentico CMS 5 Website Development: Beginner's Guide
Kentico CMS 5 Website Development: Beginner's Guide

The 3CX IP PBX Tutorial
The 3CX IP PBX Tutorial

Object-Oriented Programming in ColdFusion
Object-Oriented Programming in ColdFusion

Unity 3D Game Development by Example Beginner's Guide
Unity 3D Game Development by Example Beginner's Guide

OmniGraffle 5 Diagramming Essentials
OmniGraffle 5 Diagramming Essentials


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software