The Facebook API
May 10th, 2011, Categories: Development, Work Related
Tagged with API, Development, Facebook, JavaScript, JSON, PHP
The past year or so, I've been doing a whole lot of work with the Facebook API. It seems that there is a lot of confusion amongst both developers and project / account managers around what can and can't be done with it.
The idea of this is to give a brief overview of what's possible and what isn't. Obviously, I'm not going to go over everything, but I'm going to try and cover as much as possible without going overboard.
There are two main issues with the Facebook API itself that I want to highlight first. Firstly, the documentation is somewhere in-between shockingly awful and pure-blooded useless. It's information on each method within the API, what data it returns, how to access that data and how to get it out in the first place is very sketchy. It's documentation on it's authentication process (Facebook uses OAuth) is also close to indecipherable if you're not familiar with OAuth.
The second issue is that it changes a lot. Although they always maintain legacy support, every 6 months or so, your applications are suddenly using an old version of the API.
Despite these factors, I actually love it. Once you get the hang of using it, it's an incredibly powerful API and makes way for some really fun social application development.
Getting Started
So lets get stuck in. There are two versions of the API, the PHP-SDK (Download, Documentation) and the JavaScript SDK (Documentation).
In this article, I'm going to deal with the PHP-SDK. Perhaps I'll write another article about the JavaScript SDK at a later date. So, where do we start. Well first you need to decide what kind of data you want. If it's publicly available information (for a user for example, you can generally get their name, gender and locale - but only if you have their user ID - more on that later), you can go ahead and just access the feed for their profile (more info on this here). This feed is basically a JSON object and will return anything that you ask for that is public. For example, if I wanted to get the information for my own profile, I would do the following:
<?php
$data = file_get_contents('https://graph.facebook.com/ironhamster');
print_r($data);
?>
This will give me my user information, however, I need my user ID or my user alias. The changes of you actually having this are frankly minimal. Unfortunately, the only way to actually get this information is to authenticate the user. So how do we do this?
Setting up an app
Let's head on over to Facebook and in the search bar, search for an application called Developer. In there, you'll have the option to create a new app. Create a new app using the grey button. You'll then get asked to fill in some information, there are a lot of different options and I don't have time to go into all of them, so I'll give a brief overview of setting up a simple app.
Firstly, under 'About' give your app a name, description and add your contact email address. Privacy policy and TOS URL's aren't relevant at this time although I suggest you complete them before you push anything live.
Under the 'Web Site' tab, complete the 'Site URL' field. If you're developing locally, you can just add your local address (i.e. http://facebook-app.localhost/).
In the 'Facebook Integration' tab, only complete the 'Canvas Page' field if you want to appear on apps.facebook.com/my-app. For this demo, it's not relevant. Under 'Canvas URL', add your dev URL (as above: http://facebook-app.localhost/).
The bottom set of fields here are interesting. Facebook recently added the ability to create custom tabs on Fan Pages that are essentially an iFrame app. This allows for a huge amount of additional functional that wasn't possible before. For this, just add a quick name to the 'Tab Name' field (I've used Test) and add your development URL to the 'Tab URL' field.
Once you're done, hit 'Save Changes' and you're done. Congratulations! You've just set up your first Facebook app.
Integrating with the App
Once you've added the app, you'll be taken to a new page which will give you your Facebook App ID, API Key and App Secret. I suggest you store these as constants or something in your projects config file, although for this example I've just added them as static values at the point of instantiation.
The next thing we want to do is include the Facebook SDK, instantiate the Facebook object, check to see if the user is logged in and if they aren't, send them to the login URL, ask for permission to publish to their wall and then return them to the page. So here we go:
<?php
require_once('facebook.php');
$facebook = new Facebook(array(
'appId' => 'FACEBOOK_APP_ID',
'secret' => 'FACEBOOK_APP_SECRET',
'cookie' => true,
));
$session = $facebook->getSession();
if(!$session) {
$url = $loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email,read_stream')
);
header('Location:' . $url);
exit;
}
?>
Presuming you're already logged into Facebook (come on, who isn't?), load up your dev site and watch it redirect to Facebook and ask you for permission to post to your wall. Accept the permissions and providing you've added the correct information when you set up the app, you'll be redirect to your development site and there will be a hell of a load of junk in the URL's query string.
So what does this mean? This means you've been authenticated, accepted the permission request and now the application can use your connection to Facebook to do a whole manner of stuff. Let's start with something simple. Checking out what we have about ourselves. Add the following code after the end of the if(!$session) line and then refresh the page.
$id = $facebook->getUser();
$user = $facebook->api('/me');
print_r($user);
You should see all of the information you've added under the 'Info' tab in your profile. We've also got your Faceboook user ID. Result!
The important thing to remember is that most things that involve the user interacting with Facebook are run through the $facebook->api() method, which in turn, formats a HTTP request. There are various things you can get with this, for a full list, see http://developers.facebook.com/docs/reference/api/. It's important to remember that requesting different information usually involves asking for another permission. For example, to get the users 'likes', you'd need to ask for the permission 'user_likes' and use the code:
$data = $facebook->api('/me/likes');
For a full list of the different permission groups and what they grant, see http://developers.facebook.com/docs/authentication/permissions/.
Ok, so now we want to post to the users wall. We've already asked for and granted permission to do this, so crack on with some code. remove the last 3 lines and add the following:
$attachment = array(
'name' => 'My Post Title',
'caption' => 'Winning',
'link' => 'http://www.facebook.com/ironhamster',
'description' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'picture' => 'http://bit.ly/h8tAqj'
);
$result = $facebook->api('/me/feed/', 'post', $attachment);
Now check your news feed. Voila - a new post with a lovely picture of Charlie Sheen. Definitely winning!
The reason we assign the return value of the api() method to a variable is because it returns the ID of the new post which you can use to get via the api() method with the argument: /post/POST_ID. The post ID in this case is assigned to $result['id']. This will return an object containing the post, it's content, it's post date and time, who's liked it and who's commented on it. Very useful!
So there you go, there's a really brief intro into how to get started with the Facebook API, authenticate a user, get their information and post to their wall. Now you've got the basics, exploring the API documentation will unlock a wealth of knowledge to you and allow you to really pick up some steam with social apps.
The code for this post can be downloaded in ZIP format here
As a side note, I mentioned the realms of what is and isn't possible. Here are a few general rules that prevail through the API usage at time of writing:
- You can't get a users user ID without authenticating them with the app
- Some information is available without even instantiating the API although this information is limited. Things like info on Fan Pages and basic user info (https://graph.facebook.com/PAGE_ID or USER_ID)
- You can't retrieve who has shared content
- Although you can get a list of the users 'likes', you can't get a list of things that a user has liked externally to Facebook (i.e. if there's a 'Like' button on a blog post to 'like' the content, that won't be returned in their 'like' list when you retrieve it)
- You can't get protected information without requesting the appropriate permissions from the user
- You can include all the functionality you could include in an iFrame app, in an iFrame tab (very useful)
- You can perform most or all of the functionality available via the PHP SDK, with the JavaScript SDK
- Some Facebook functionality (i.e. Questions) at time of writing, doesn't have any API integration
- To my knowledge, you can't externally host, or re-skin the login or permission request pages (unless you're creating a desktop application or mobile app)
- It is possible to pass data to an iFrame tab page. Add the URL parameter 'app_data' to the Facebook URL (i.e. www.facebook.com/PAGE_NAME?sk=app_2405167945&app_data=some+data) and add the data there. To retrieve it, on your page, use the getSignedRequest() method. It'll appear in the resulting array.









