“Facebook API 101″ by presenter Jonathon Hibbard
In this presentation, I hope to provide you with as much information as possible to start building your own very basic applications based on Facebook’s great API model. The API model, while unknown to many developers, is quite simple. However, getting started with it can be very challenging (as with any API, or new concept that one may (or may not) be unfamiliar with).
Since the Facebook API has close to a hundred PHP functions, and easily over a thousand FBML (Facebook Markup Language) tags and settings, we will instead just focus on the very basics to get you on your way.
The following topics will be covered in this presentation:
- Steps for getting your first Facebook Application registered and ready for the Facebook Community.
- Setting up your directory that will host your facebook application.
- Getting and unpacking the Facebook API class files.
- Configuring the Facebook Application settings.
- Understanding the basics of the FBML and the actual PHP Classes associated with this API.
- How to setup a basic DB-driven application to be used with Facebook’s API (examples included)
- Helpful sites, and starter tutorials that can also help
From Facebook’s Developer page, they suggest you know or need the following:
- You should be well versed in PHP or some other coding language — such as Ruby on Rails, JavaScript, or Python — especially one that has a client library for our API.
- You need to have a basic understanding of the Internet, SSH, MySQL, and Unix
- You need to be familiar with Web hosting fundamentals and have a place to host your application.
I would add that you should also be familiar with XML as the syntax for FBML is similar to a small degree, and it will only make learning this markup language easier.
So, without further ado, let’s begin.
I. Steps for getting your first Facebook Application registered and ready for the Facebook Community
While understanding Facebook’s API, FBML, FQL, and FJS is very important for building a Facebook application, we must also understand the principals involved with registering our application and obtaining the necessary Keys to interact with their environment (just like we do with Google Maps or any other 3rd party site who has an API we wish to use).
First we need to Login to the Facebook Developer section. To do this, we’ll go to their developer landing page (http://developers.facebook.com/get_started.php), and click “Go to the Facebook Developer App”. If you notice, the login looks the same as if we were trying to log into facebook normally, but they have a redirect in that sends us to the Developer’s section we will need to be in to register our application.
On this page, we’ll simply click “Set Up New Application”. This is where we finally start defining what our application will be named, hosted, etc.
The first screen we see is the Application Name. This name can be changed at any time, so we will just use something generic, Accept their terms, and go on our way.
What we are directed to next is what you will become quite familiar with over time: the application settings page. This page (as I stated earlier) not only allows you to change the name of your application, but also :
- Is where you’ll find the API Key / Secret Key that you’ll use through Facebook’s API connection to be granted access.
- Where you can define how your application will be presented to your audience (ie: Description, Icon, Logo, etc)
- Where you define the location of your application that lives on your own personal hosting platform
There are many other settings and things you can do on this page, but the basics I’ve stated above are what we need as the rest is out of scope of this presentation. We will revisit these settings in a minute.
For now, let’s leave the settings page and grab the Facebook API and start setting up the environment on our hosting server where our tool is going to live.
II. Setting up your directory that will host your facebook application.
Setting up your directory to host your Facebook Application is nothing really spectacular. You’re still going to need to create the directory in the htdocs of your web hosting environment, and you’re still going to need the same access rules for loading images/css/html pages as you should already be accustomed to.
For our example, we’ll be creating a directory named oinkpug_101 which will be where our facebook application is going to live.
Inside of our oinkpug_101 directory, we’ll be creating a small hierarchy of directories.
First, we’ll create the apps directory that will contain 2 directories: classes and includes.
cd oinkpug_101 mkdir apps cd apps mkdir classes mkdir includes
Inside of the classes folder, we’ll create a directory named facebook that will be where we’ll host the facebook API.
cd classes mkdir facebook
While there are a number of directory structures one can create, and I’m sure that’s a debatable subject among many developers, this is my method i use for creating structure.
Feel free to use whatever method suits you and your needs the best.
And that’s all there really is to it. Now we’re ready to get Facebook’s API package and install it into its new home.
III. Getting and unpacking the Facebook API class files.
Obtaining the Facebook API can be accomplished many different ways. The two I will suggest are :
- By clicking “PHP Client Libraries” in the Helpful Links section of the original page we were on (http://developers.facebook.com/get_started.php)
- By using wget from the console and downloading directly to your server environment (wget http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz)
As with many things in life, there are many other methods and choices, but for me these are the 2 easiest to cover in this introduction.
I’ll be using the second method for wget to obtain the package, and then extract this tar ball into the directory we created earlier for it (facebook):
cd oinkpug/apps/classes/facebook wget http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz tar xvfz facebook-platform.tar.gz
If we do a directory listing we’ll now see the directory structure this API uses. In it, there are 2 main directories: footprints and php.
The footprints directory is just an example Facebook has given you for understanding how to interact with your own personal Database (which we will cover later).
For now, the only directory we are concerned with is the PHP directory, which houses the actual API classes and methods that we’ll be using.
The php folder has 1 subfolder (JSON) and 4 PHP class files (facebook.php, facebook_desktop.php, facebook_mobile.php, and facebookapi_php5_restlib.php).
The subdirectory JSON contains the JSON classes for sending/recieving JSON data. This directory will not be covered in this presentation as it is out of scope for a 101 talk. The main purpose of it though is Facebook’s API sends the vast majority of your method calls to their server by an encapsulated JSON request/response method that will send/receive the data you are requesting/sending.
Instead let’s look at the 4 php files that are in the root of our php directory. facebook.php is the main class file that’s used. It’s sole purpose is to create a connection and handle your initial requests for accessing user/friend information through the FacebookRestClient.
The facebookapi_php5_restlib.php is the FacebookRestClient class that our main Facebook class calls. The FacebookRestClient basically is the nuts and bolts of the actual API to obtain user/group/application information from Facebook’s server through the JSON class we spoke about earlier.
The other 2 files are facebook_mobile.php and facebook_desktop. As their names imply, the mobile php file is used for developing mobile applications, while the desktop php file is used for creating desktop applications. Just like the JSON class, we will not be covering these two files since they are out of scope for what we are wanting to achieve.
However, there are useful links included in our references point that can guide you in the right direction should you want to explore these alternatives.
Now that we have our files unpacked, and have a very basic understanding of what files we are now hosting (to the world no less), we’re ready to start setting up our Facebook application settings and also actually creating our first facebook application to be used with Facebook.
IV. Configuring the Facebook Application settings.
Configuring your facebook application settings is very simple.
We first switch back to Facebook’s Application Settings page we left earlier.
Under the “My Applications” section, we’ll click on our Application Name (ABC123).
Next we’ll click Edit Settings and you’ll notice we’re right back into the Application Settings page.
Here, our next step should be clicking on the Canvas link located on the left hand side of this page. The first section we’ll find here is “Required URLs” that facebook needs us to define in order to direct request for your applications to not only the facebook application URL (labeled Canvas Page URL on this page), but also the path to where your application is accessed via URL (labeled Canvas Callback URL).
The first url, Canvas Page URL, is going to be something we define that best suits what our application name will be. Our application’s name is abc123, so in the first text box for http://apps.facebook.com/, we’ll put abc123.
In the Canvas Callback URL, we’ll put http://www.phpadvocate.com/OINKPUG_101 .
Since we’ll be using the Facebook Markup Language (FBML), we’ll switch the Render Method of FBML.
Finally, we’ll click save to commit our changes which directs us back to the summary page for our application.
You’ll notice on this page that Facebook happily gives us our API Key, Application Secret key, and Application ID instead of forcing us back into the application settings page. It also gives us the link we can use while logged into facebook to access our Application which we will use in few minutes to view our first facebook application.
There also exists one more important item, which is labeled Sample Code on this page. If you click on this link, you’ll notice a div that opens up containing not only a very simple PHP script, but also that they have went ahead and populated your API key and Application Secret key in the code for you. So, we’ll go ahead and copy this text so that we can create our first facebook page right away with the least amount of trial and error.
We’ll switch back to our editor that we’re using for managing our php files and create our first file in the oinkpug_101 directory.
I’m going to name our first file index.php so that it’s our landing page, paste the code.
If we look at the code, the first thing we see is the require_once of facebook.php. Our path right away needs to be updated to point to the correct location of facebook.php.
So, we’ll just add the correct path and save our changes.
So, what does this code actually do? That bring us to our next section.
V. Understanding the basics of the FBML and the actual PHP Classes associated with this API.
When we examine this file we’ll see that line 13 shows us how we instantiate the facebook class by passing the api key first, then the application secret second.
The very next line is a foreign to us at the moment and it’s not quite clear what it does. So, let’s look at Facebook’s require_login method definition to see if they have some help for us.
When we read this comment, that tells us absolutely nothing right? So how are we supposed to know that we even need this function? When the code doesn’t leave us with the proper comments, we resort to Facebook’s Developer Wiki.
If we go to Client Libraries, then PHP, we’ll be directed to the Official PHP client Library Page. A simple search for require_login will take us to a section explaining this function as follows:
require the user to be logged into Facebook before using the application. If they are not logged in they will first be directed to a Facebook login page and then back to the application's page. require_login() returns the user's unique ID which we will store in fb_user
Obviously their comment says fb_user, but our code says user_id. Either way, the definition and point is quite clear. We’re basically just forcing the user to be a valid, logged in user to access and use our application. Once validated, the method just returns us their User ID which we will use now to get whatever information we can that facebook can offer to our application.
In our example, we are going to get their name using the FBML and their friends list using an API call.
We’ll first examine the FBML call works to get the current user’s name and information.
If you know anything about XML (or any other markup language), you’ll see why I said XML is good to know to understand FBML as the syntax is very similar.
We’re basically creating a tag, and applying some values to it. However, while the syntax may appear the same, it’s purpose and results are very different.
To understand this piece of code, we’ll again resort to Facebook’s Wiki. Instead of client libraries, we’ll just scroll down to Reference and click the FBML link.
On this page, we’ll do a simple search for fb:name (since this is the tag we just ran into), and we’ll click the link it’s associated with.
As you can see, Facebook does a really good job at explaining this simple (yet complex) markup they have created. While the complex part of it will make it difficult to just jump in head first and try to swim, the Wiki they have provided us with simplifies it (and all the other available FBML tags) drastically to take out a lot of uncertainty as to what we need and don’t.
You’ll notice that in the Attributes section for fb:name, there is a table structure for the possible definitions: Required, Name, Type, and Description.
Required determines what is absolutely necessary to use this FMBL tag. Optional, of course, means you don’t really have to use it, but can be used to obtain whatever it is that tag can obtain with the required field.
In our code, we are only concerned right now with uid and useyou.
The uid is (as one might expect), the actual user id we received from our initial require_login api call.
The “useyou” definition can at first glance not be so easy to understand. It basically says “if the uid you are passing is equal to the current user who is accessing your facebook application, then show the word YOU instead of the user’s actual name.”. So, since our setting is false, we can assume we’ll see the actual display name of the required UID.
To prove this point, we’ll test out this definition by saving our changes and opening the url to our application (http://apps.facebook.com/oinkpug/). You’ll notice on this page, we see Hello, Jonathon Hibbard!
So, let’s see if we can make it say “you” by switching the false to true in the FBML tag fb:name.
Notice when we refresh the page, we indeed see “you”. We also can notice that either you or the user’s name is a link, which directs you to their profile page.
See how simple this fbml really is? It’s a simple matter of going back to facebook’s wiki, finding a tag that we want to either use or learn about, and just clicking and reading.
OK, let’s continue. On line 22, we’ll notice there is the following call: $facebook->api_client->friends_get();
Obviously $facebook is our facebook object, but what is api_client? If we open facebook.php, we’ll see right away that api_client is defined as a public variable, and if we scroll down to the construct of the facebook class, we’ll notice that public variable is being loaded as the FacebookRestClient object (which I spoke about earlier that is basically just the nuts and bolts of accessing the specific facebook data via JSON).
So, we now know that we’re basically just calling the FacebookRestClient object and looking for the method friends_get();
This time, when we view the code for the FacebookRestClient class and search for the friends_get method, we’ll be presented with a very nice description of just what it does.
Notice the pattern? We refer to the class files first for their definition, and then if we can’t find a valid definition, we resort to the facebook wiki. And if the wiki fails (which it is very possible) to give us the information we need, there is always the greatest tool on the Internet: google.
But this time, we get exactly what we want. The definition and meaning behind the method we’re calling.
Now that we have this, let’s switch back to our index.php file.
The next few lines may or may not be very familiar to most. Either way, here’s what’s going on:
While our $friends array, we’re going to grab only the first 25 friends. Then, we’re going to loop through these friends and display each key’s value.
When we view our application page again, this time we’ll notice exactly what that list of numbers was: user id’s.
But what can we do with these id’s? How do we get the actual human readable names that correspond to each of this id’s?
Instead of complicating this question more by doing a google search, we must first look for the most simple answer that’s right in front of us. Can anyone guess?
We can do it by using the FBML tag we used to obtain the currently logged in user’s name in the first place.
So, for echo “<br />$friend”;, let’s replace it with a FBML call!
echo “<br /><fb:name uid=\”$friend\” />”;
When we refresh our page now, we’ll get the list of names we were looking for!
So, what if we actually wanted to do a bit more, like save changes, or have the user input some information for us?
VI. How to setup a basic DB-driven application to be used with Facebook’s API
This final section is probably the most complex of them all. While we only have a very small understanding of Facebook’s API model and the FBML, creating a DB-Driven application can get very complicated quickly, thus resulting in an overwhelming feeling that you’ll never get it. Then again, maybe it’ll be very easy for you. Either way, each person is different, but the thing you have to keep remembering is that this is nothing more than just one more thing you’re trying to learn to better yourself as not only a developer, but a current/future employee. Facebook is gaining a LOT of attention, and saying that you know (or are in the process of learning) their API model should impress your employer (or future employer) at the very least.
While I could go on a huge tangent about all this, we’ll instead just do what developers do to learn something foreign: jump in head first.
Thankfully though, once again Facebook has provided us with an example of creating a simple DB and event driven application which i mentioned earlier: footprints. There does, however, exist a problem with this example (which has yet to be fixed), but I’ve already commented the fix in the code (which we’ll get to after seeing the error).
For now, let’s just open the directory and see what there is to see.
cd apps/classes/facebook/footprints
Inside this directory you’ll see 4 files: config.php, index.php, lib.php and README
Since we’re new to all of this, let’s first look at the README fle. Once again we’ll see that the complexity of this API (which we talked about earlier) is met with simplicity from Facebook’s explanation of what exactly we’re looking at here.
So we know that, first, we’ll want to open the config.php and update it with the necessary database connection information. We’ll also have to either get our API/Secret keys from the application settings page, or we can just copy it directly from our existing index.php file.
When examining config.php, we’ll notice there also exists a CREATE TABLE definition as the README indicated. I’ve already created this table (along with the database of oinkpug), so we’ll just skip this step.
Once our config.php file is setup and saved, we now need to determine how we want to test this application out.
There exists 2 methods: 1) we can create a whole new application on facebook along with a directory on our hosting server, or 2) we can just backup index.php in our current oinkpug directory and copy the files in footprints into that base directory.
For this presentation, we’ll just use method 2 as it’s quicker and easier.
Now that we have the files backed up and copied over, let’s open up our new index.php file and see exactly what’s happening in this example.
First, we’ll notice that we’ll have to update the require_once to point at our actual path to the facebook.php class file.
We’ll also see that there are 2 more includes: lib.php and config.php
The lib.php file is basically a list of methods that we’ll be using for this page, along with it’s actions (we’ll visit this file real soon). And of course, we already know that the config.php file holds our keys and database connection information.
As we move down the file, we notice our now familiar instantiation of the facebook object, but instead of immediately requre_login we have a new method call: require_frame();
While Facebook’s class definition doesn’t really explain what this function is/does and the facebook wiki doesn’t help either, we have to resort to google for an explanation.
A quick search will lead us to the facebook forums which has a few posts on the subject. In a nutshell, the require_frame() function basically says that you must be inside facebook to execute this application. In other words, if we try to just access our application via url (http://www.phpadvocate.com/oinkpug) you’ll notice we get directed immediately to the canvas url of this application. The catch to this is we don’t really even need this, as require_login does the same (plus returns the user’s id), but for the sake of argument, we’ll leave it in.
Next we see that we’re checking for a posted value to exist named To. We also notice 2 functions that are being called from lib.php : do_step and get_prints.
Skimming down to line 29, we’ll notice that we’re opening up a div with some basic HTML and then also find our already visited fb:name FBML tag. The very next line calls yet another new method: get_add_url. This function basically just gives the user a link to add your application to their profile if it doesn’t already exist.
After this, we find a small if statement that is checking a $prints_id to our $user id.
When/If our IF statement rings true, we see that we’re presented with a simple FB:NAME FBML tag again that’s asking if we want to step on a user which appears to be a confirmation question.
When our IF statement rings false, we notice a brand new FBML tag: fb:friend-selector. This FBML tag (as we will see in just a second) is just one of MANY Ajax-controlled tags that presents us with a dynamically driven look up for searching our friends list for names.
Next, we’ll see our familiar FB:NAME FBML tag, but this time with a new attribute inside of it: possessive. This tag basically works as the useyou attribute, only possessive displays the word YOUR.
Finally, we see our last method call: render_prints() which we will learn about once we view the lib.php file.
So now, let’s just load up our application. When we do, we’re presented with a nice simple form, and we’ll notice the new search box that’s in the middle of the page. This is what makes the FBML such a lovable markup. They take all the hard work of creating an Ajax-driven search box that looks like Facebook’s environment, and makes it available to you in one simple line of code!
However, after we type in the name we are looking up, and press Step, we notice right away there are 2 errors that show up:
Warning: Missing argument 3 for FacebookRestClient::notifications_send(), called in /oinkpug_101/lib.php on line 52 and defined in /oinkpug_101/apps/classes/facebook/php/facebookapi_php5_restlib.php on line 1450 Fatal error: Call to undefined method FacebookRestClient::feed_publishActionOfUser() in /oinkpug_101/lib.php on line 58
WTF right? Well, this is actually not your fault here, this is an issue with Facebook’s example having errors and outdated code. You can view this this forum page for a fix, or just follow these steps:
- Open lib.php
- Find the function do_step (which is causing all of our problems…)
- Add a string as the 3rd paramater for the $facebook->api_client->notifications_send call (ie: $result = & $facebook->api_client->notifications_send($to, ‘ stepped on you. ‘ . ‘<a href=”http://apps.facebook.com/footprints/”<See all your Footprints</a>.’); becomes $result = & $facebook->api_client->notifications_send($to, ‘ stepped on you. <a href=”http://apps.facebook.com/footprints/”>See all your Footprints</a>.’), ‘app_to_user’;);
- Finally, replace the function call $facebook->api_client->feed_publishActionOfUser to be $facebook->api_client->feed_publishUserAction. The reason is publicActionOfUser no longer exists in the API and was instead replace with publishUserAction…
- Save and refresh your page. Presto! Fixed.
Now, if we go through this lib.php file, we will start to see all of our very common SQL calls, also new FBML calls, and even some new FB API calls! Will I go into them now? I doubt time has spared us that much. So the ball is now in your court to do the wonderful world of discovery against this great API. After all, we just scratched the service, and where better to pick up than from a simple example?
Good luck, and I hope this presentation has been helpful in some way.
VII. References
http://wiki.developers.facebook.com/index.php/FBML - FBML Introduction / Usage List
http://wiki.developers.facebook.com/index.php/Category:FBML_tags – Alphabetical Listing of all FBML Tags (click one to get more information)
http://wiki.developers.facebook.com/index.php/FQL – FQL Introduction / Usage List
http://wiki.developers.facebook.com/index.php/FQL_Tables – FQL Table Schemas..
http://wiki.developers.facebook.com/index.php/User:Client_Libraries – PHP Client Library explanations/help
http://forum.developers.facebook.com/ – The Facebook API Forums
http://www.phpeveryday.com/articles/Facebook-Programming-My-First-Facebook-Application-P847.html
http://forum.developers.facebook.com/viewtopic.php?id=27548 – BUG FIX FOR FOOTPRINTS EXAMPLE CODE