Thursday, February 18, 2010

Using Facebook API and using FQL

Using FQL Facebook Query Language



Preliminary


So you've made a facebook application, and you want to start using FQL to query all sorts of interesting things from Facebook's massive database of users

Facebook FQL Programming APIs



There are many API's available for facebook to access the FQL language. Some are for PHP and there are some for python (my favourite).

Aparently there is also one available using HTTP at the following url:


https://api.facebook.com/method/fql.query?query=QUERY


We will be using PHP. You must download the Facebook PHP client library. In our PHP script, we include the main file as shown:

include_once '/path-to-api/facebook-platform/php/facebook.php';


Diving In



Next, we create our instance of our facebook object:


$facebook = new Facebook('API_KEY','SECRET_KEY');
$fb_user = $facebook->require_login(); //require that we log in, because we need the user's id


Make sure you replace the API_KEY and SECRET_KEY with the proper strings, or also you could use php's define. Now what I wanted to do with FQL is generate a list of all the "Pages" that I have created under my account. I created well over 100 so I needed an easy way to get that list. Here is the example FQL query:


SELECT
page_id,
name,
page_url,
fan_count
FROM
page
WHERE
page_id IN (SELECT uid, page_id FROM page_admin WHERE uid = {$uid})


(Edit)
Note: FQL does not support standard SQL like JOIN, thus we use the subquery shown and the IN operator.

We use the client fundion "fql_query" in order to return the results of this query. Note I have {$uid} in there, that must also be replaced with the user's ID who created all those pages. Here is the PHP code I used for this:


$uid = $facebook->api_client->user; // get the user id
$query = "SELECT page_id, name, page_url, fan_count FROM page WHERE page_id IN (SELECT uid, page_id FROM page_admin WHERE uid = {$uid})";
$res = $facebook->api_client->fql_query($query);
print_r($res);


There you have it! For more info on FQL see the official API documentation here:

FQL Documentation
List of FQL Tables available for query
Sample FQL queries

No comments:

Post a Comment