Wrangling with the Facebook Graph API

Have you ever wanted to learn how to make your applications more social with Facebook? It's much easier than you think!

In this tutorial, we'll be building an application that reads and publishes data to and from Facebook using Facebook's Graph API. Interested? Join me after the jump!


A Short Introduction to the Open Graph Protocol

Facebook Open Graph

Open Graph Protocol

Image courtesy of http://ogp.me

The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook.

While many different technologies and schemas exist and could be combined together, there isn't a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement. Developer simplicity is a key goal of the Open Graph protocol which has informed many of the technical design decisions.

In a nutshell, the Open Graph Protocol turns any web page into an object in a huge graph. Each object, at least in Facebook's graph objects, can have many other objects linked to it. For example, a Facebook Page can have multiple Post objects, which are posts made by that page. In turn, each Post object can have multiple Comment objects attached to it, referring to comments written by people on the post. This relationship between graph objects is the basis for Facebook's Graph API, which in turn allows us to do CRUD operations on these objects.

In this tutorial, we'll be learning how to use and integrate the Facebook Graph API into an application. We'll also learn how to use data from the Graph API to do operations like logging in a user via their Facebook account. Ultimately, we'll be creating a small application than allows people to create and read posts from a Facebook Page they're managing, similar to HootSuite or TweetDeck.


Step 1: Create a Facebook Application

The first thing you should do when you're planning to use the Facebook Graph API is to create a Facebook application. This doesn't necessarily mean that we'll be putting the application on Facebook (although we can); we just need a Facebook application (specifically an APP ID and APP SECRET) to access the API.

Open http://developers.facebook.com and click on the Apps link in the navigation bar.

Facebook's Developer Site

Facebook's Developer Site

You'll be prompted to log in (if you're not) and allow the Developer application to access your account. Just click on Allow and you'll be redirected to the Developer App homepage.

Allow the Developer application access

Allow the Developer application access

On the Developer App homepage, click on Create New App in the upper right corner of the page.

Developer App homepage

Developer App homepage

You'll be greeted with a modal window asking for an App Display Name and App Namespace. Provide anything you want here, but for the purposes of this tutorial, I'll be using Nettuts+ Page Manager and nettuts-page-manager respectively. Click on Continue.

Birth of the Nettuts+ Page Manager

Birth of the Nettuts+ Page Manager

After some obligatory captcha checking, you'll be redirected to your newly-minted application's page. Here you'll see the APP ID and APP SECRET that we need. Copy and paste these values somewhere for later use.

The APP ID and APP SECRET

The APP ID and APP SECRET

When that's done, go to the lower part of the page and click on the “Website” box, and below it should appear a form that asks for a Site URL. Since I'm just using my local machine to build the application, I'll use http://localhost/nettuts/pagemanager. When you're done, click on the Save Changes button below.

Nettuts+ Page Manager Settings

Nettuts+ Page Manager Settings

Step 2: Download and Set Up Facebook's PHP SDK

Facebook's GitHub page

Facebook's GitHub page

Our next task is to download and set up Facebook's PHP SDK. The best location to get it would be on Facebook's GitHub page, since this is where the latest and greatest version of the PHP SDK will be.

Downloading Facebook's PHP SDK

Downloading Facebook's PHP SDK

Point your browser to https://github.com/facebook/php-sdk and click on the “ZIP” button. This should prompt a download for the latest version of the SDK. Save it anywhere you like.

Now, extract this into PHP's include_path to make it accessible by any application. Alternatively, if you're just using this for one application, extract it inside the application's folder — just make sure to take note where, since we'll have to include facebook.php in our code later.


Step 3: Read from Facebook via the Graph API

Let's start creating our project and using the Facebook Graph API to read information from Facebook. For starters, create an index.php file where a user can log in via Facebook. The index.php file should contain the following code:

If you're wondering, reset.css is just your standard stylesheet reset, and bootstrap.min.css is Twitter Bootstrap. I've also added jQuery into the mix to make it easier to do client-side stuff. Now, if you refresh the page, it should look something like this:

Nettuts+ Page Manager First Run
Nettuts+ Page Manager First Run

Now let's create our connect.php file, which will enable us to connect a user's Facebook account and the pages that he or she manages. Let's start by including the Facebook library we downloaded earlier. Instantiate it using the APP ID and APP SECRET:

The $facebook variable can now be used to make API calls to Facebook on behalf of the application.

  • The appID setting tells Facebook which application we're using.
  • The secret setting “authenticates” our API calls, telling Facebook that they came from someone who owns the application. This should never be shown to the public, which is why it's named the “Application Secret.”
  • The cookie setting tells the library to store the user's session using cookies. Without it, we won't be able to know whether the user is logged in via Facebook or not.

Now, we check if the current user has already allowed access to the application. If not, the application has to redirect them to Facebook's “Allow Permissions” page.

Essentially, this is all that happens here:

  • The application makes a simple API call to get the user's Facebook User ID (also known as FB UID) via the $facebook->getUser() method.
  • If the $user variable has a value, it means that the user has already allowed basic permissions for the application.
  • If not, then it means the user hasn't allowed the application permissions yet, and the application needs to redirect to Facebook's permissions page to get the necessary permissions.
  • It then generates a Login URL, which is where the application should redirect the user to show Facebook's permissions page for the application. The getLoginUrl() method takes in the following parameters:
    • scope - this is a comma-delimited list of permissions the application needs
    • fbconnect - this should be 1 to tell Facebook that the application will be using Facebook to authenticate the user
    • redirect_uri - this is the page Facebook redirects to after the user has gone through the Facebook permissions page

    You can read more about the getLoginUrl() method here: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

  • Afterwards, the application redirects the user to the Login URL and the user sees Facebook's permissions page.
Facebook's Permissions Page

Facebook's Permissions Page

Facebook Permissions

Let's take a minute to talk about Facebook permissions. Similar to when you install an application on your Android phone, Facebook permissions are various levels of access a Facebook application can do on behalf of a user. For example, if we wanted access to user's email address, we can add the email permission to the scope setting we use to generate the login URL.

Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

It's important that your application only asks a user for permissions that it actually needs. If you only need to authenticate a user via Facebook, you don't even need to ask any permissions at all! Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

In the app, we use the following permissions:

  • publish_stream - allows the application to publish updates to Facebook on the user's behalf
  • read_stream - allows the application to read from the user's News Feed
  • offline_access - converts the access_token to one that doesn't expire, thus letting the application make API calls anytime. Without this, the application's access_token will expire after a few minutes, which isn't ideal in this case
  • manage_pages - lets the application access the user's Facebook Pages. Since the application we're building deals with Facebook Pages, we'll need this as well.

There are a lot more permissions Facebook requires for different things. You can read all about them in Facebook's documentation for permissions.

Going back to the application, now that the user has allowed the permissions required by the application, we can do some API calls to Facebook! Place this inside the if-else block from the code above:

The first thing we do is get the $access_token for the user that the application just authenticated. This is crucial, as the application will need this access token for almost everything we do. To get it, we use the getAccessToken() method. The $access_token acts as a 'password' for the user. It's always unique for every user on every application, so make sure to store this when needed.

Afterwards, we can see how to make API calls to Facebook using the api() method. This method takes in the following parameters:

  • $graph_path - this is the Facebook graph path, which is essentially the “URL” to the open graph object we want to access. This can be any graph object on Facebook, like a Post (e.g. '/<post_id>'), a Comment (e.g. '/<comment_id>'), or even a User ('/me' is a shortcut for the current user whom the $access_token belongs to. It can also be '/<user_name>' or '/<fb_uid>', but the $access_token you're using must have access to that user, or you'll only be able to get the user's public information).
  • $method - this is the kind of method you want to do. It's usually GET when you're trying to “get” information, and POST when you're trying to “post” or update information and DELETE if you want to remove information. If you're not sure, the Graph API documentation tells you which method to use for specific API calls.
  • $params - these are the parameters that come with your API request. Usually for GET methods you only need to supply the user's $access_token. For POST methods though, you'll also need to provide other parameters. For example, if you want to post a new status update, you'll provide the status update message here.

Alternatively, we can also use the api() method to execute FQL (Facebook Query Language) queries, which lets us get data via SQL-style language. This is great for retrieving information not available in the Graph API, as well as running multiple queries in one call. For example, we can get a user's name and other details through this FQL API call:

We won't need this for this tutorial, but it's good to keep this in mind when you come across something the Graph API can't get.

Now that we have the list of permissions the user has allowed for the application, we need to check if the user gave the application all the necessary ones. Since Facebook's permissions page allows users to revoke certain permissions, we need to make sure that all of them have been allowed to make sure the application works. If the user has revoked one of the permissions, we'll redirect them back to the permissions page.

var_dump() of the $permissions_list variable

var_dump() of the $permissions_list variable

When that's done, it means we're all set and we'll be able to run the application without any problems. Let's start by doing another API call, this time to retrieve the list of Facebook Pages the user has administrative rights to, and saving these into a session variable. Afterwards, we'll redirect the user to the manage.php page, where the page management code will be.

var_dump() of the $accounts variable

var_dump() of the $accounts variable

The /me/accounts graph path gives us a list of the pages that a user has administrative rights to. This returns an array of all of the pages, plus specific $access_tokens for each of these pages. With those $access_tokens, we'll be able to do API calls on behalf of the Facebook Page as well!

Save these in the $_SESSION array and redirect to the manage.php page.

Let's start working on our manage.php file. Remember that we've saved the user's $accounts list into the $_SESSION array, as well as set the first account on the list as the default active page. Let's GET that account's news feed and display it:

Again, the application does the intialization of the Facebook library, and then another api() call, this time to /me/feed. Take note that instead of using the user's access token, we use the active page's access token (via $_SESSION['active']['access_token']). This tells Facebook that we want to access information as the Facebook Page and not as the user.

var_dump() of the $page_feed variable

var_dump() of the $page_feed variable

Wow, that's a lot of information about a Facebook Post. Let's dissect a single Facebook Post object and see what it's made of.

The Facebook Post Object

Facebook Post Cheat Sheet

Facebook Post Cheat Sheet
  • id - this is the Post's ID
  • from - contains information about the user who posted the message
  • message (red) - the message component of the post
  • picture (orange) - a link to the photo attached to the post
  • name (blue) - the “title” of the Facebook post
  • link (also blue) - the link to where the name goes to when clicked
  • caption (purple) - a few words to describe the link
  • description (pink) - more than a few words to describe the link
  • icon (grey) - a link to the icon image used
  • actions - Facebook actions you can do to the post, such as Liking it or Commenting on it.
  • privacy - the privacy of the post
  • type - the type of the post. A post can be a status, link, photo or video.
  • created_time - the time when the post was created
  • updated_time - the time when the post was updated
  • comments - comments on the post

It would be wise to keep a copy of the cheat sheet above, since we'll be using that again when we publish Post objects to Facebook.

Moving on, let's display the news feed in a more pleasing way. Add the following HTML below the PHP code:

We make use of a simple Graph API trick here: the Picture Graph API object. Basically, you can take the Graph path of any User or Page object (e.g. http://graph.facebook.com/293518907333589), add /picture in the end and you'll get a 50x50 photo of that object. For example:

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

Becomes...



Demo Picture Graph API Object

Going back, when we refresh the manage.php page now, it should look something like this:

Add this inside the <?php foreach($page_feed['data'] as $post): ?> to display the feed from the page:

When you refresh the page again, it should look something like this:

Looks good, right? We'll have to thank the Twitter Bootstrap CSS for that!

Now, let's add a top navigation bar to help us switch from one page to another. Add the following HTML after the <body> tag and before the <div id="main" class="container"> tag:

Don't forget to load the dropdown JavaScript library from Twitter Bootstrap's JavaScript page. You can download it here.

Lastly, let's create the switch.php file, where we'll set another page as the active page:

Refresh the manage.php page again and you should see something like this:

And now, by using our dropdown switcher, we're able to switch pages.


Step 4: Publish to Facebook via the Graph API

Now we're ready to publish new updates to our page! First of all, let's create the HTML form where we can set what we'll publish. Add this below the <h3>Post a new update</h3> HTML:

Refresh to see how it looks:



Loving Twitter Bootstrap's default form styles

The Post cheat sheet should come in handy when we're figuring out what to put in the fields. Now, let's create the newpost.php file where we'll actually use the Facebook Graph API to publish to the page's feed.

Start by creating the file and initializing the Facebook library like we did for the other pages:

Afterwards, let's get all of the content we received from the POST request:

Let's not forget to add the $access_token for the page to the parameters:

Now that we have our $parameters array, let's build and send our Graph API request!

Take note of what difference the $method can make. A GET API call to /me/feed will return the news feed of that particular object, but a POST API call to /me/feed will post a new status update to the object.

To publish a new Post object to Facebook, the application needs to make a call to the /<page_id or /me>/feed graph path, and it needs to supply the following in the $parameters array:

  • access_token - the access token of the account we are publishing for
  • message - the message to publish
  • picture (optional) - a link to the photo of the post
  • name (optional) - the “title” of the post
  • link (optional) - a link to where the name will go to when clicked
  • caption (optional) - a few words to describe the link/name
  • description (optional) - more than a few words to describe the link/name

You can see that the only parameters that are required are the access_token and the message parameters. By providing only these two, we can publish a simple status message, like so:



Status Update Example

Everything else is optional. However, if you provide a name, link, caption, or decription, you have to provide all four. As for picture, if a parameter value is not provided or not accessible, the post's picture will be blank.

Finally, let's try publishing to Facebook using the application! Go back to the manage.php page and fill up the form, then press Post:

Afterwards, you should be redirected back to the manage.php page, but there should be a new post on the feed!



Publishing to Facebook successful!

You can also check the Facebook Page itself. You should see the new post there:



Publishing to Facebook Page

Conclusion

By now, you should already have a clear grasp on how to use the Facebook Graph API to both read and publish to Facebook. In this tutorial, we only cover the basics — there's a whole lot more you can do using the Graph API. Stuff like real-time updates, which lets you subscribe to events that happen to your application's users (e.g. when a user changes his/her profile photo) or the Insights Graph object, which lets you get the statistics of an application, page, or domain the user has access to.

Of course, the best resource for learning more about the Graph API is undoubtedly Facebook's Graph API documentation, but I also suggest taking a look at FBDevWiki, which is a third-party hosted wiki for Facebook Development documentation.



FBDevWiki.com

Additionally, there's also a special Facebook version of StackOverflow you can visit at http://facebook.stackoverflow.com. The questions here are all about Facebook and Facebook Development, so it's well worth visiting if you need any help or have any questions on the subject.



Facebook StackOverflow

Hopefully, you've learned from this tutorial how easy it is to use the Facebook Graph API to make your applications more social.

Have you used the Facebook Graph API in a previous project, or are you planning to use it now? Tell me all about it in the comments below and thank you so much for reading!

Tags:

Comments

Related Articles