Facebook Application Development

Do you have a Facebook page? If you do, you are among the 600 million users who actively use the social-networking service. I'll admit I initially resisted the temptation to join Facebook. After all, I've got e-mail, instant messaging and VoIP. What do I need with yet another form of communication? Eventually, temptation got the better of me, and I gave it a try. For the record, I also experimented with MySpace and Twitter, but those sites just didn't seem to do anything for me. These days, every time I go to my computer, I check my servers, my e-mail and my Facebook.

I never thought it would get to this point, but it turns out that Facebook is a surprisingly powerful piece of technology. So far, I've connected with friends from church, college, high school, previous jobs and some of my son's activities. I've managed to reconnect with my best friend from high school after 20 years. I've even managed to reconnect with my best friend from the third grade! Since I'm 43 years old, I think that's quite an accomplishment. Like I said, it's very powerful technology.

But for me, there's more. I also get links to blogs and news articles from like-minded friends as well as pointers to breaking news that's of interest to me. Many times, I've heard about events on Facebook before I saw them on TV or read about them in the newspaper. Lately, I've been investigating ways to use Facebook to promote my new business, and I'm sharing some of what I've found in this article.

First, let's take care of some of the easy stuff. Everyone's probably been to a Web site and seen a Facebook "Like" button. When users click on this button, they are asked to log in to Facebook, if they're not already. Then, the button click causes a brief message to be added to users' Facebook pages, indicating that they like the particular Web site. All of the users' Facebook friends then can see this message. Assuming that many of one's friends share the same interests, this is a very simple way to get a message out to potentially interested people.

Adding a Like button to a Web site is as easy as embedding a little HTML code into your page. Facebook even has a wizard to help customize the button: https://developers.facebook.com/docs/reference/plugins/like.

When I played with this wizard, I was given code that looked like the code shown in Listing 1. This code results in a Web browser displaying something that resembles Figure 1.

Listing 1. Like Button Code


<iframe src="http://www.facebook.com/plugins/like.php?href=
&rarrhk;www.linuxjournal.com&amp;send=true&amp;layout=
&rarrhk;standard&amp;width=450&show_faces=true&action=
&rarrhk;like&amp;colorscheme=light&amp;font&amp;height=80"
 &rarrhk;scrolling="no" frameborder="0" style="border:none; 
 &rarrhk;overflow:hidden; width:450px; height:80px;" 
 &rarrhk;allowTransparency="true"></iframe>

Figure 1

Figure 1. Like Button

Facebook also provides methods that allow a Web site to post to users' Facebook pages as well as adding a person or page to their friends list. These methods are documented at https://developers.facebook.com/docs/reference/dialogs.

Before I go any further, let me pass on a little tidbit of information I came across while researching this article. Facebook supports a primitive chat function that allows users to exchange interactive messages with their friends. This chat function is based on the XMMP protocol, which is the same protocol that Google Talk and Jabber use. The details are documented at https://developers.facebook.com/docs/chat. Essentially, you need to know your Facebook user name and password. Then, you prepend your user name to @chat.facebook.com to form a Jabber ID. When I plugged this information in to Kopete, I was able to chat with my Facebook friends using Kopete. I also was able to get real-time updates when my friends logged in and out of Facebook.

Facebook also provides a powerful method of querying its database for various types of information. Using a language called Facebook Query Language (FQL), you can ask for all kinds of information about a Facebook user, subject to access restrictions. The easiest way to do this is to use the HTTP GET access method. This method allows you to execute a query using a standard HTTP GET. The results are returned in XML format. All you have to do is append your query to the end of this URL: https://api.facebook.com/method/fql.query?query=.

For example, if you had a user ID number and wanted to find the user's full name, you would use something like this:


https://api.facebook.com/method/fql.query?query=select 
 &rarrhk;name from user where uid=1690577964

 

Amazingly, your results look like this:


<![CDATA[
<fql_query_response list="true">
       <user>
               <name>Mike Diehl</name>
       </user>
</fql_query_response>
]]>

 

FQL requires that you specifically list each of the fields in which you are interested. That means you can't simply use select * from... as you would be tempted to do in a language like SQL. So, it's important to know what tables and columns are available to you. This is well documented at: https://developers.facebook.com/docs/reference/fql.

At the risk of duplicating what's already on the Web site, here's a list of a few of the more interesting tables that you can query (from the Web site):

  • comment: query this table to obtain comments associated with one or more feed comment XIDs.

  • connectioncomment: query this table to return a user's friends and the Facebook pages to which the user is connected.

  • friend: query this table to determine whether two users are linked together as friends.

  • like: query this table to return the user IDs of users who like a given Facebook object (video, note, link, photo or photo album).

  • notification: query this table to get the notifications for the current session user—that is, any notification that appears on http://www.facebook.com/notifications.php.

  • profile: query this table to return certain (typically publicly) viewable information from a user's profile or Facebook page that is displayed in a story.

  • status: query this table to return one or more of a user's statuses.

  • stream: query this table to return posts from a user's stream or the user's profile.

  • user: query this table to return detailed information from a user's profile.

You can query against quite a few other tables, and I've not fully explored what information is available. I can tell you that e-mail addresses and phone numbers aren't readily available using this query method. Also, users are able to set permissions that determine what can be retrieved.

That said, you could use these methods in a server-side program to get all kinds of information about a user. But, the real power comes from being able to perform these queries on the client's computer via JavaScript. (I'll show you how that's done, shortly.)

Before you can do anything even remotely fun with Facebook's JavaScript API, you need to become a developer. Becoming a developer is a simple matter of adding the "developers" application to your Facebook profile and filling out a form, which is available at https://www.facebook.com/developers. Once you've filled out the form and agreed to the Facebook terms of service, you can start adding and configuring your new applications. You'll be issued an application key for each application you define. (I'll explain how to use that key shortly.)

Facebook has received a lot of bad publicity lately because of its often-changing and sometimes poorly implemented privacy policies. But, from reading its terms of service, which all developers have to agree to abide by, it appears that Facebook is really trying to do the right thing. Some items from the terms of service, for example, stipulate that you can't spam your users. That is, you can't create pre-canned messages and blast them out to multiple users. You always must provide an "opt-out" for any action your application performs. You're not allowed to store personal data for use outside your application and so on. Facebook's terms of service all seem pretty rational and are documented at https://www.facebook.com/terms.php.

Now that all the formalities are out of the way, let's define our first application. Start the process by going to https://www.facebook.com/developers/createapp.php, and create a new application (Figure 2). Once you've created your new application, you have to configure it.

Figure 2

Figure 2. Create New Application

There are a half-dozen pages of configurable options, so I won't go into too much detail with them. Most of them are fairly intuitive and well documented. As long as you understand the process that Facebook performs when a user accesses your application, you won't find this very difficult. Because understanding the process is critical, I'll discuss it a bit before looking at some more code.

The key concept is that all Facebook applications occupy a space on the Facebook interface known as a canvas. The canvas is where your application's content will be rendered and is embedded inside the rest of the Facebook look and feel. Essentially, a Facebook application developer simply uses the Facebook JavaScript API and server-side code to perform the application's function. Thus, you can write your server-side code in any language you like.

When users access your application, they use a URL that looks like http://apps.facebook.com/APP_NAME, where APP_NAME is the name given to your application. So, if I created an application called mikestestpage, it would be accessible as http://apps.facebook.com/mikestestpage. You'll notice that this URL points to a Facebook page. When the user's browser loads this page, Facebook sends a page back to the user, as expected. However, Facebook also embeds the content of your application's canvas code. The end result is a seamless integration between the Facebook user experience and your program code.

To keep this from getting too abstract, let's look at the code shown in Listing 2.

Listing 2. Facebook JavaScript Demonstration


 1 #!/usr/bin/perl
 2   
 3   
 4 print <<EOF
 5 Content-Type: text/html; charset=ISO-8859-1
 6   
 7   
 8 <http>
 9 <head>
10 <title>test page</title>
11 </head>
12 <body>
13   
14 <script src="http://connect.facebook.net/en_US/all.js"></script>
15   
16 <div id="fb-root">
17 </div>
18   
19 <hr><span id="who"></span>
20 </hr>
21 <p>
22 <div id=result>
23 </div>
24   
25   
26 <script>
27 var user_id;
28   
29 var r;
30   
31 FB.init (
32    {
33   appId  : '206854775749',
34   status : true,
35   cookie : true,
36   xfbml  : true 
37   }
38 );
39   
40 FB.getLoginStatus(t, false);
41   
42 function t (response) {
43   
44   if (response.session) {
45     r = response;
46   
47     var query = FB.Data.query('select name, uid from user 
       &rarrhk;where uid={0}', r.session.uid);
48   
49     query.wait(
50       function(rows) {
51          document.getElementById("who").innerHTML = 
            &rarrhk;rows[0].name + "\'s Minions!";
52       }
53     );
54   
55     var query2 = FB.Data.query('select uid1, uid2 from 
       &rarrhk;friend where uid1={0} order by uid2', r.session.uid);
56     query2.wait(
57       function(rows) {
58          var i = 0;
59          var friends = "";
60   
61          while (rows[i]) {
62              var friend = "<img width='20px' height='20px'
                &rarrhk;src=http://graph.facebook.com/" + rows[i].uid2 
                &rarrhk;+ "/picture> ";
63              friends = friends + friend;
64   
65              if ((i%20) == 19) { friends = friends + "<br>"; }
66              i++;
67          }
68   
69          document.getElementById("result").innerHTML = friends;
70       }
71     );
72   
73   } else {
74     FB.login(function(response) {
75       if (response.session) {
76          // user successfully logged in
77       } else {
78          // user canceled login
79       }
80     });
81     r = null;
82   }
83 };
84   
85   
86 </script>
87   
88 <p>
89 <fb:like href="http://apps.facebook.com/mikestestpage/" 
    &rarrhk;width="450" height="80"/>
90   
91 </body>
92 </http>
93 EOF
94 ;

This is a simple Perl script, but it's meant to be as language-agnostic as possible. All it does is output some static HTML. Lines 1–13 are simple boilerplate that produce a valid HTTP and HTML header. Line 13 loads the Facebook JavaScript API. I discovered that my application didn't work unless I included the code in lines 16 and 17; Facebook must use that DOM container internally. The rest of the code is the fun part.

Lines 19–23 create the simple application's layout by creating a who and a result DOM container. The rest of the code is devoted to populating those containers. It's all done in the JavaScript starting on line 27.

Lines 31–38 are where you initialize the Facebook API by passing it an object that contains, among other things, your application's unique identifier. Line 40 calls the getLoginStatus method and passes it two parameters. The first parameter is a callback function that gets called when this method returns. The second parameter has to do with authentication caching; I found that if I set it to True, my callback was called twice, which didn't work very well.

The main code is in the callback function in lines 42–83. Line 44 checks to see if the user is logged in. If not, the else statement block on lines 73–82 is executed. In this simple application, users will be given the opportunity to log in and then must reload the page. More sophisticated applications would reload the page for them, of course.

That leaves lines 45–71. Line 47 creates an FQL query, as discussed earlier. All this query does is get the user's name. Lines 49–53 use the wait method to get the results and process them using a callback function that you pass implicitly as a parameter. Here, all you're doing is creating a string value with the query results and placing it inside the who DOM container. The fact that this method is called wait is a bit of a misnomer. This is not a blocking call. This function will be called asynchronously as the results are returned to the client.

In lines 55 and 56, you set up another query and process the results in another callback function. Only this time, the query selects all of the current user's friends by UID number. The callback function, in lines 57–70 loops over that result set. Each time through the loop, you build up an IMG tag that points to the thumbnail picture of each of the user's friends. On line 65, you ensure that you start a new row of pictures after every 20 pictures are rendered. Finally, you send all of the image tags, en masse, to the result DOM container. The browser then begins to load the images.

And, that's the bulk of the application, except for that little piece of magic on line 89. The <fb:like> tag is a tag that Facebook interprets before it sends the results to your application's canvas. In this case, you're asking Facebook to provide you with a Like button that your users can press to indicate to their friends that your program is worth trying. There is an entire class of such tags, known as the Extensible FaceBook Markup Language (XFBML), and I've barely scratched the surface of what's available. This article was meant as a teaser to let you know that this functionality is available.

Figure 3 shows the results of this simple application.

Figure 3

Figure 3. My Minions

As you can see, Facebook has a huge user base and provides many powerful ways to interact with those users. I've demonstrated a couple neat tricks you can use with your own Web pages, as well as provided an introduction to the Facebook Javascript API. I've also briefly shown how to integrate your application into the Facebook framework. I hope this has been fun, and I hope it piques your interest in Facebook application development.

Load Disqus comments