Although the FQL language isn’t ANSI-SQL complete, it does have some simple operators and functions to help you work with user data. FQL has boolean operators (AND, OR, and NOT), comparison operators (=, >, >=, <, <=, <>), and arithmetic operators (+, -, *, and /). The functions included in FQL, although not exhaustive, allow you to perform some basic string manipulations. To conserve bandwidth, you can use the concat() function to group several tuples together:

<?php

$facebook_config['debug'] = false;

$facebook_config['api_key'] = '<your_api_key>';

$facebook_config['secret_key'] = '<your_secret_key>';

require_once('<path_to_client_library>/facebook.php');

$facebook = new Facebook($facebook_config['api_key'],

$facebook_config['secret']);

/**

* Ensure the user has logged on to Facebook

*/

$user = $facebook->require_login();

/**

* Construct the FQL request

*/

$fql = "SELECT concat(first_name, ' ', last_name)

FROM user

WHERE uid = '$user'";

/**

* Pass the FQL to Facebook through the API client

*/

$fql_result = $facebook->api_client->fql_query($fql);

/**

* Print the results to the screen

*/

echo "<pre>FQL Result:" . print_r($fql_result, true) .

"</pre>";

?>

The previous example simply selects the first and last names of the user who is currently making the request. The resulting page will display an array in the following format:

FQL Result:Array

(

[0] => Array

(

[anon] => <your_first_name> <your_last_name>

)

)

You might be saying to yourself, “This is pretty useless. What’s the difference between this and just calling both the fields?” Well, if you have any bandwidth concerns, you can alleviate some of those issues by using the concat function to put fields that you need together. For instance, you might want to put a specific string into your page that combines several fields in a specific way. Letting the Facebook servers do some of this processing before it gets back to your server will not only decrease your server load but can also cut down on your bandwidth in order to speed up your application.


Not only can you do simple SQL-style selects, but you can also perform subqueries. Take, for example, this FQL equivalent for the facebook.events.get REST API call:

SELECT eid, name, tagline, nid, pic, pic_big, pic_small, host, description,

event_type, event_subtype, start_time, end_time, creator, update_time,

location, venue

FROM event

WHERE eid IN (SELECT eid FROM event_member

WHERE uid=uid AND rsvp_status=rsvp_status) AND

eid IN (eids) AND

end_time >= start_time AND

start_time < end_time

I won’t go into the theory behind nested queries, but I will mention that they are very useful for testing set membership, set comparisons, and set cardinality. And, this expansion of the REST call serves as a good example for writing your own custom FQL expressions.

You might find that you will need to take some additional processing to make sure your information is displayed in a specific order. You’ll have to do this with your client language. For PHP, you need to sort the array and then slice it. Let’s take the following:

<?php

$fql = "SELECT eid, name, location

FROM event

WHERE eid IN (

SELECT eid

FROM event_member

WHERE uid = '$user'

)";

$fql_result = $facebook->api_client->fql_query($fql);

asort($fql_result);

array_slice($fql_result, 0, 5);

?>


The previous passes an FQL query to find events for the current user, sorts the resulting PHP array, and returns the array with the six elements (positions 0–5) of the query result.

FQL allows you as a developer to have granular control of the information that you retrieve about your users from the Facebook servers. Although it’s not as robust as you might sometimes need (or want) it to be, you can generally get around FQL’s limitations with some post-processing in the language in which you’re developing. Additionally, as the complexity of your FQL increases with subqueries, you might at some point run into problems. As I’ve mentioned earlier, using the Facebook API Test Console at http://developer.facebook.com/tools.php is a great place to help debug your code. For instance, if you take the previous query and take out the WHERE clause so that your FQL statement reads as follows:

SELECT eid, name, location

FROM event

WHERE eid IN (

SELECT eid

FROM event_member

)
then, when executed, this will raise an error because you must have a limiting WHERE clause. If you missed it when you look at your code, the resulting XML response shows an error code of 601 and an error message of “Parser error: WHERE clause is required.” Fortunately, this is an easy fix, but you might find yourself working with more complicated interactions with FBML and FQL, and this tool can provide invaluable help in discerning where your bugs exist.

Here’s a list to make sure you know what’s available to you in the different tables. (OK, these aren’t really tables; more likely these are views of specific data, but for simplicity’s sake, we’ll just call them tables.)

  • users(uid, first_name, last_name, name*, pic_small, pic_big, pic_square, pic, affiliations, profile_update_time, timezone, religion, birthday, sex, hometown_location, meeting_sex, meeting_for, relationship_status, significant_other_id, political, current_location, activities, interests, is_app_user, music, tv, movies, books, quotes, about_me, hs_info, education_history, work_history, notes_count, wall_count, status, has_added_app)
  • friend(uid1, uid2)
  • group(gid, name, nid, pic_small, pic_big, pic, description, group_type, group_subtype, recent_news, creator, update_time, office, website, venue)
  • group_member(uid, gid, positions)
  • event(eid, name, tagline, nid, pic_small, pic_big, pic, host, description, event_type, event_subtype, start_time, end_time, creator, update_time, location, venue)
  • event_member(uid, eid, rsvp_status)
  • photo(pid, aid, owner, src_small, src_big, src, link, caption, created)
  • album(aid, cover_pid, owner, name, created, modified, description, location, size)
  • photo_tag(pid, subject, xcoord, ycoord)

If you’ve worked with SQL before (and I assume you have), FQL isn’t a big deal. You use the same syntax as typical ANSI-SQL, and there are only nine tables to deal with. There are, however, some important differences. There are no joins, and FQL has not implemented the LIMIT, GROUP BY, or ORDER BY clauses that are common to ANSI SQL–compliant implementations.

Facebook also has implemented an API for basic database manipulations with its Data Store API. This API provides a basic create, read, update, and delete (CRUD) API for storing data that you access through REST. If you’re unfamiliar with object-oriented database management systems (OODMSs), some of the terminology is a bit different from that for relational database management systems (RDBMSs). For instance, to use the Data Store API, you must define your schema (your database), which consists of object types (tables) and properties (columns).

One of the really nice features of the Facebook Data Store API is that Facebook does not plan to charge for normal use! You basically have use of Facebook’s servers to perform your database manipulations for you. However, it’s probably not quite time to get rid of your RDBMS yet, because there aren’t any structured queries, full-text search, or transaction-level query processing in the Facebook Data Store API.

Note:
Data Store API may be in beta stage. Please consult the wiki documentation for the latest information before you deploy any projects using the Data Store API.

The Data Store API consists of three basic functions: specialized tables, distributed tables, and associations that are split into five separate APIs (User Preference, Object Data Definition, Object Data Access, Association Data Definition, and Association Data Access). Since Facebook provides access to millions of users, the tables (objects) you create are distributed. Facebook does provide a specialized table of users that is optimized (if you find that you really need more, let the Facebook developers know at their Bugzilla site, http://bugs.developers.facebook.com/). The associations component of this API is a mechanism to provide performance for fast lookups (such as indexes). Because indexing tables in a distributed environment won’t necessarily provide a performance boost, this mechanism has been implemented to provide fast lookups without centralized indexes or parallel queries.

The user preferences for the API consist of 128-character strings, for which you can store up to 201 for each user (numbered 0–200). Access to the getters/setters are accessed through getters and setters in the REST API (facebook.data.setUserPreference and facebook.data.getUserPreferences).

Data objects (that is, tables) are created with facebook.createObjectType. The object type takes a name and contains a set of object properties (that is, columns). Object properties have names and data types. You don’t quite have the same type of control over the data types with the API as you do with your own RDBMS because you are limited to integers, strings (less than 256 characters), and text blobs (with a maximum of 64KB).

After defining your objects and object types, you create, read, update, and delete through the Object Data Access API. These are rather straightforward (facebook.data.createObject, and so on).

To work with the associations between objects, you first need to define the relationship between objects in the facebook.defineAssociation call. You can define two types of associations: one-way, symmetric associations and asymmetric associations. If you’re familiar with RDBMS joins, think of an asymmetric association as a many-to-many join and a symmetric association as a one-to-many join. One-way associations are an association between objects that can happen only one way (in other words, there’s no need to look up a value by some ID) for a given object. You then create the actual associations with the Association Data Access API. These methods allow you to create, remove, and retrieve these associations and retrieve the object details from the data contained in the data definition.

This can be confusing at first, so let’s look at an example:
<?php
$createObject = $facebook->api_client->data_createObjectType("wallpost");
$uid = $facebook->api_client->data_defineObjectProperty("wallpost", "uid", 1);
$time = $facebook->api_client->data_defineObjectProperty("wallpost", "timePosted",2);
$post = $facebook->api_client->data_defineObjectProperty("wallpost", "post", 3);
?>

The previous snippet of code is analogous to the following SQL DDL:
CREATE TABLE wallpost(
uid integer,
timePosted timestamp,
post text
)

As you can see in this simple example, this can take a little bit to get used to because you’re not performing your typical SQL DDL; however, once you get your mind around how to create the objects, it’s relatively trivial to use the API as the persistence layer for your application. I suspect that this API will eventually make it out of beta and be quite a powerful tool in the Facebook developer’s toolbox, at least for those who choose to have Facebook manage their data.

Sometimes when you’re developing an application, you make mistakes. Fortunately, Facebook returns rather robust error messages when something goes wrong (like you forgot to provide a specific parameter for an API call). The error codes are returned with both a numeric value and a message. Generally, if you receive an error message (in a structure), it’s rather obvious when you read the error message (in the err_msg element). If you can’t figure out what’s going on with a specific call, it’s always a good idea to check out the code in the API Test Console (http://developer.facebook.com/tools.php). Although this won’t give you any more information than you are getting returned, it can help you narrow down what’s going on (in case you have multiple errors).

The final set of methods in the REST API gives you access to some user information for your application. The first, facebook.users.isAppAdded, tells you whether the user has added your application. To get information from your user’s profile, you can call the method facebook.users.getInfo. Lastly, to get the user ID (uid) from a session key, use the facebook.users.getLoggedInUser method.

To easily interact with setting information in the user’s profile, there are two methods to work with, facebook.profile.setFBML and facebook.profile.getFBML. These methods allow you to set and get FBML for a user’s profile box and profile actions.

With more than 60 million images added each week by Facebook users, there are several REST methods to interact with users’ images. You can tag images with the facebook.photos.addTag method or create photo albums with the facebook.photos.createAlbum method. You can get a user’s individual photos with the facebook.photos.get method or a listing of their albums with the facebook.photos.getAlbums method. You can also get the listing of the tags that individual photos have with the facebook.photo.getTags method. You can also upload photos with the facebook.photos.upload method.

Facebook allows you to send and receive notifications in your application with the REST API. You can expose your user’s request notifications, by using the facebook.notifications.get method, to see outstanding notification responses. You can also send notifications to your users with the facebook.notifications.send method and send invitations with the facebook.notifications.sendRequest method.

Facebook’s marketplace is a place to buy/sell items, list jobs, list housing, or even request items to purchase/borrow through Facebook. You’re able to search the Facebook marketplace with facebook.marketplace.search. There are getters and setters for listings with facebook.marketplace.getListings and facebook.marketplace.createListing. You can also remove listings with facebook.marketplace.removeListing. Facebook also has a category and a subcategory getter method, facebook.marketplace.getCategories and facebook.marketplace.getSubCategories.

If you want to work with your user’s groups, the REST API has two methods that return information about their visible groups. When you call the facebook.groups.get method, you can retrieve all the groups the user belongs to, or a subset of these groups, by using the method’s filtering mechanism. The second method, facebook.groups.getMembers, returns the user IDs (UIDs) for a given public group.

When you’re developing applications, you might find it necessary to look at the friends of your users. There are three methods provided to deal with this. The method facebook.friends.areFriends will tell you whether two people are friends. The facebook.friends.get method returns a structure of the user’s friends’ user IDs. Lastly, the facebook.friends.getAppUsers method returns a structure of the friends of the user who have installed the application on which you’re working.

Most of the calls in the REST API are wrappers for complex, but common, FQL queries. The facebook.fql method takes a query and returns a response object based on your syntax. In the Facebook documentation, most of the API requests have their FQL equivalents, so if you see you need something slightly different from what is provided in the API calls, check out the FQL equivalents before you start writing from scratch.

To update a user’s news feed, the REST API has two methods. To publish information to an individual user’s feed, the facebook.feed.publishStoryToUser method will publish information to a user’s feed based on their session key (session_key) and their user ID (uid). You add the title, body, and various links, depending on what you want to publish. The second method, facebook.feed.publishActionOfUser, publishes a mini-feed story to the user’s account, also based on their session key and user ID.

To deal with some of the more advanced features of FBML, Facebook has three API methods to help you. The facebook.fbml.refreshImgSrc method fetches and caches an image at a given URL. To refresh content from a given URL, you use the facebook.fbml.refreshRefUrl method. Lastly, to use content as a handle in FBML, you can call the facebook.fbml.setRefHandles method.

Event calls have two main wrappers to retrieve information on events. The first, facebook.events.get, returns a response based on the filters passed to it. The second, facebook.events.getMembers, returns the RSVP status for Facebook members for a given event.

The REST API has two methods for dealing with authenticating your users. The method facebook.auth.createToken creates an authentication token (auth_token) that is then passed to the Facebook authentication mechanism. After the user is logged in, the second REST method, facebook.auth.getSession, will contain this token in the response, but only if you specifically request the auth_token in the response.

Authentication is usually (at least when it’s done well) a big headache for developing online applications. Because Facebook takes responsibility for these actions, you don’t have to purchase SSL certifications, implement your own encryption schema for passwords, or even worry about sessions. In the case of the PHP client library, you start the authentication procedure by calling the Facebook object’s require_login method. By calling this method, your users are redirected to Facebook’s login pages (https://login.facebook.com/login.php), which are passed your API key, and the user is given a session key and redirected to your callback page. The only difference is that when the user enters the application for the first time, they are asked to accept the terms of service for the application.

Now, you might find yourself in need of performing some task (such as updating FBML), but instead of logging into Facebook every time, you want to update the data to use some sort of scheduled task. You are able to do this with an infinite session key.

The process to get your infinite key is a bit convoluted (but, hey, you have to do it only once for each application). After creating your application, create a new page (infinite_key.php) in your callback domain that creates a new Facebook object and echoes your session_key:
<?php
/**
* @title infinite_key.php
*/
$facebook_config['debug'] = false;
$facebook_config['api_key'] = '<your_api_key>';
$facebook_config['secret_key'] = '<your_secret_key>';
require_once('<path_to_api>/facebook.php');
$facebook = new Facebook($facebook_config['api_key'],
$facebook_config['secret']);
// force a login page
$user = $facebook->require_login();
$infinate_key = $facebook->api_client->session_key;
echo($infinate_key);
?>

Once you have this code on your server, log out of Facebook, clear your Facebook cookies and browser cache (just to make sure nothing funky is going on), and then go to the page you just created on your server (that is, not the application URL, but the actual URL). You will be asked to log on again, so do so, but make sure you check the No Longer Have to Log In to Facebook box. After you’ve logged on, you should see the infinite key that you can then use in your code.

You can now use your own UID and key in other code to perform anything that needs to happen on a regular basis with the set_user function in the facebook object:
<?php
...
$uid = '<your_uid>';
$key = '<your infinite key>';
$facebook->set_user($uid, $key);
// code that needs to be executed
?>

The infinite key is a powerful construct for your Facebook application that you might find you need to implement. Most of the folks who have needed this are updating FBML for features such as mini-feeds or pushing content to their user’s profile page.

Facebook has some rather convenient out-of-the box tools for interacting with its back end. At the core of the platform is a set of API calls that wrap more complex code into a single call. In fact, most of the API calls are simply wrappers for complex FQL calls. So, without further adieu, let’s take a look at what you have available to you through the API calls.

Facebook’s API methods are broken into logical groups of calls. These API calls are also where your first interaction with the platform comes into play. You don’t need to use the client library—it just makes things faster since you would need to write these in your language in order to interact with the platform.

To set up the client library for PHP, you simply include the client library in your code. For example, the following snippet makes sure users are logged on to Facebook before displaying a list of the user’s friends. Below Figure shows the results.
<?php
'; $facebook_config['secret_key'] = '';/** * include the Facebook client library */ require_once('/**
* Set the configuration settings for Facebook
*/
$facebook_config['debug'] = false;
$facebook_config['api_key'] = '<your_api_key>';
$facebook_config['secret_key'] = '<your_secret_key>';
/**
* include the Facebook client library
*/
require_once('<path_to_client_library>/facebook.php');
/**
* Set up the facebook object
*/
$facebook = new Facebook($facebook_config['api_key'], $facebook_config['secret']);
/**
* Ensure the user has logged on to Facebook
*/
$user = $facebook->require_login();
/**
* Make an API call to call get a user's friends using the PHP library's
* library
*/
$friends = $facebook->api_client->friends_get();
echo "<pre>Friends:" . print_r($friends, true). "</pre>";
?>

You’ll notice a few things in this example. First, you’re just throwing the results from the friends object on the screen. I’ll cover interacting with the resulting code with FBML a bit later. Second, the syntax for interacting with the API is abstracted into methods in the Facebook object. You first set up the Facebook object with the API and secret keys that Facebook assigns to you when you set up your application.


You’ll also notice that you require the user to be logged on to Facebook in order to execute the code. This example uses the require_login() method and stores the user’s identification number (UID) in the variable user. The next call actually queries the Facebook API method friends.get by wrapping it in the PHP method friends_get. Since the facebook object holds the user’s identification number (their primary key or UID), there’s no need to pass the UID to the API request. From this short sample code, you can see that the PHP code is actually setting up a REST client to call the facebook.friends.get API method and returns an array of user identifiers:

/**

* Returns the friends of the current session user.

* @return array of friends

*/

public function friends_get() {

if (isset($this->friends_list)) {

return $this->friends_list;

}

return $this->call_method('facebook.friends.get', array());

}
The client libraries allow you to concentrate on developing your application rather than recoding your interactions with the platform. Since you need to know what you can do with the API.

The official client libraries written by Facebook are of the PHP and Java variety. Other language libraries are listed on the Facebook developers web site, but in the interest of simplicity, I’ll cover only the PHP library (specifically the PHP 5 library). If you’re working with other languages, most of the concepts should be the same, but depending on how the developer who wrote the library chose to implement certain elements (and the characteristics of the language the libraries are being implemented in), the way methods are called and named might be slightly different. As a word of warning, some libraries are better documented than others; some have web sites replete with example code, and others have just a link for a download. If you run into a problem and you can’t get help with your language-specific version, take a look at the documentation for the “official” client libraries for PHP or Java.

Facebook’s PHP client library consists of two main object classes, Facebook (in facebook.php) and FacebookRestClient (in facebookapi_php5_restlib.php). As you might expect, the FacebookRestClient class abstracts interactions with Facebook’s API. The Facebook class utilizes the FacebookRestClient class’s methods to further abstract common interactions with the Facebook platform. For instance, instead of writing a procedure to require a user to have a session key to work with your application, the Facebook object has a method named require_login() that checks for the session key and, if it doesn’t find one, redirects the user to Facebook to perform the authentication and then returns the user to your application.

You use the classes just like any other PHP class with require_once (or your other favorite way to create objects):
<?php
/**
* Include the Facebook PHP client library
*/
require_once('<path_to_client_library>/facebook.php');
/**
* Set your API and secret keys
*/
$api_key = '<your_api_key>';
$secret_key = '<your_secret_key>';
/**
* Initialize a new instance of the Facebook client object
*/
$facebook = new Facebook($api_key, $secret_key);
?>
Your API and secret keys are assigned to you in your My Applications portion of Facebook’s Developer application (http://www.facebook.com/developers/apps.php). Once instantiated, the Facebook client libraries make it easy to interact with the Facebook platform.

If you actually look at the code in the library, you’ll notice that it contains a few different classes. For instance, when you create a Facebook object, that class is including a library to make the REST calls (facebookapi_php5_restlib.php). If you are using PHP to write a desktop application, the main change is that you would use the facebook_desktop.php file, which extends the Facebook object but is better suited to desktop applications. The facebookapi_php5_restlib.php file is the real workhorse for your application and is where you will find most of the functions you will use in your application.

One nice aspect is that the developers of the Facebook platform used phpDoc conventions, so generating complete documentation for the platform is relatively simple. If you don’t have a version of PhpDocumentor, you can download it from SourceForge at http://sourceforge.net/projects/phpdocu/ or use PEAR to install it: pear install PhpDocumentor

PEAR should install a new script that you can call from the command-line script, which you then can call to create the documentation: phpdoc -t /path/to/output -d /path/to/facebook_client_library -pp on –ti Facebook
Client Documentation
This line will set the output directory (-t), take a look at the client library path (-d ), parse private functions within the code (-pp), set an HTML title of “Facebook Client Documentation” (-ti), and then output the results in HTML using frames. There are many more options for producing documentation, but these options will produce very useful documentation while you develop your Facebook application. For more information about using this tool, check out the phpDocumentor web site at
http://www.phpdoc.org/.