Facebook Fans Count Using Python and the Graph API

I noticed some peeps struggling to show off their Facebook fans count on their websites using the Facebook API. I’ve shown before on how to do it in PHP, and this quick post is about Python. Honestly, you’ll laugh as soon as you read the following three lines of code:

import facebook
graph = facebook.GraphAPI()
print "Mashable has %s fans" % graph.get_object('/mashable')['fan_count']

Yeah, and that is one more reason to love Facebook. Now, you might be wondering where I got that Facebook module I imported? It’s called the Facebook Python SDK, it’s free and open source, hosted at Github and seems to be official.

There’s other info about public objects available via that method as well, you can get a full list by printing the whole object which is a dictionary:

print graph.get_object('/mashable')

Don’t forget to cache objects since you wouldn’t like to fire requests at Facebook every time your page loads up. If you’re thinking about other Graph API methods, make sure you read the Authorization section in the Graph API Overview since you’ll need OAuth tokens to make requests.

Heh, maybe I should continue this series of posts for a dozen of other languages too? ;) Thanks for sharing!

WordPress and Magic Quotes

This is crazy, and based on a post called WordPress and PHP magic quotes: you want to run me crazy! by Stefano Lissa. I’m writing a plugin prototype for WordPress that uses the new Facebook Graph API to post stuff to my wall on Facebook (upcoming blog post). The original Facebook PHP SDK comes in very handy when working with the Facebook API, and I had quite some fun using it, but..

I’ve been trying to figure this out for hours! I had code working outside WordPress and once I pumped it into a plugin it suddenly stopped authorizing me. I had to dig through the facebook.php code to figure out what’s happening, and here it is. The getSession() method uses the get_magic_quotes_gpc function and strips the slashes from the $_COOKIE superglobal if it’s switched on. Of course, that’s the correct logic supporting both php 5 and php 6, but not WordPress.

I looked through the latest (3.0.1) WordPress core code and was quite surprised to see a function called wp_magic_quotes(). Oh my god, thought I! Commented as: Add magic quotes and set up $_REQUEST ( $_GET + $_POST ).

What the hell is that? Okay, let’s see:

$_GET = add_magic_quotes($_GET);
$_POST = add_magic_quotes($_POST);
$_COOKIE = add_magic_quotes($_COOKIE);
$_SERVER = add_magic_quotes($_SERVER);

How does that sound? So all my apps, plugins, external libraries working with server variables (like Facebook does with cookies) are not allowed to use the magic quotes function? This means that working with WordPress, we must initially assume that all these are quoted, no matter what the php settings are. I don’t even know what question to ask here, perhaps: Is this the way things are done? Why?

To be honest this is getting me a little frustrated. Not by the fact that they’re slashing the whole input (although I don’t see a reason to) but, heh, I’ve been coding based on WordPress for over two years now, and never came across anything like this. Did I miss something in the Getting Started guide? ;) Anyways, the easiest way to get this working is to replace your get_matic_quotes_gpc function with 1, which says it is always switched on.

Eh, Monday morning disappointment ;) Cheers, and thanks for sharing the post!

Counting Facebook Fans in PHP: The Graph API Way

In a previous blog post called How to Count Facebook Fans in PHP I’ve shown a code snippet of how to count the number of fans on a fan page using PHP. Times have changed, the Graph API has been introduced, and due to some responses I introduce here the new way of retrieving your fans count using the new Graph API and php.

Before you copy and paste, flush my comments with ‘my code is not working’ posts, I’d like to get your attention to versioning of the Facebook PHP SDK which we’ve been using all this time. The SDK has changed and of course the old method doesn’t work with the new SDK which is mostly tuned to Graph API, therefore, my previous code still works on a dozen on websites, because I have the old SDK installed back there. So please, be careful to what you download and use, read release notes and change logs, it will save you hours of googling.

The following snippet is based on the Facebook PHP SDK version 2.1.1 (use the Switch Tags option on github to browse through different tags). So get a fresh copy of facebook.php and have it somewhere nearby.

Unlike the old FBQL way, the new Graph API is much easier to work with, and retrieving the fans count is literally two lines of code (initialization doesn’t count). Here’s the snippet to retrieve the fans count for Mashable (don’t forget to replace your application ID and API secret):


$facebook = new Facebook(array(
	'appId' => 'your-app-id',
	'secret' => 'your-api-secret',

$mashable = $facebook->api('/mashable');
echo 'Mashable has ' . $mashable['fan_count'] . ' fans';

Easy as that! I was also surprised to see that the Graph API is doing so well. Yeah, the documentation is not very rich, but whenever you need to retrieve something from Facebook, you can always print_r the results, which gives you the full picture. Sending data into Facebook is a little trickier and I’ll show you how in a later blog post.


How to Count Facebook Fans in PHP

Update: There’s an new easier way of retrieving the fans count using the Graph API, covered here: Counting Facebook Fans in PHP: The Graph API Way

Not too tricky this one, but very handy as the social media world is developing extremely fast. It may not be too useful to publish the fan count of your facebook fan page if you’ve got less than a hundred or so, but as soon as you jump that high, it’s a good idea to show people that they’re not the only ones following you. Same applies to Twitter and other social media platforms.

The code is fairly simple if you’re familiar with the Facebook API, and even easier if you ever used the Facebook Client for PHP library, which makes tackles this issue in (literally) three lines of code and a simple FQL query. Don’t forget that in order to work with the Facebook platform, you’ll need an API key and secret. If you haven’t got a developer account, follow this guide to set it up.

That’s probably the most difficult part of this article. Once you have a dev account and the PHP client library, all you do is:

$facebook = new Facebook('api_key','api_secret');
$fql = 'select fan_count from page where page_id = your_page_id;';
$result = $facebook->api_client->fql_query($fql);
$fb_fans = $result[0]["fan_count"];

Please note! that the code above is fine for the old version of the Facebook PHP Client. They released a new one which handles things a little bit differently, so here’s the code for the new version (tested in 2.0.4):


$facebook = new Facebook(array(
  'appId'  => 'your_app_id',
  'secret' => 'your_app_secret',
  'cookie' => true,

$result = $facebook->api(array(
	'method' => 'fql.query',
	'query' => 'select fan_count from page where page_id = your_page_id;'

$fb_fans = $result[0]['fan_count'];

Replace api_key and api_secret with your own keys and secrets, replace your_page_id with the numerical ID of the page you’d like to quote. Also, if you’re unsure what is returned, then you should run a few checks on $result using print_r or var_dump.

Well.. That’s it! I just came across this issue last week and thought somebody might find it useful. Also note that in order to optimize the load time of your page, you should cache the result for some time, perhaps a day or two. Same applies to Twitter followers count and anything else you’re doing via public APIs (unless you’re using a javascript widget of course).

The Facebook Platform: Building a Custom Fan Page

As you may have heard, I’m only starting as a Facebook developer and with a few recent experiments, Timothy and I thought about customizing a fan page on Facebook, which will hopefully soon take advantage of its own domain name (Facebook’s Open Graph API). This is less of a technical post and more of a thinking one. We started our new experiment on a Sochi 2014 Olympiad fan page on Facebook and we’re trying to replicate one of the the original websites (sochi2014.com) inside the fan page canvas.

Errm.. I’d like to give a huge shoutout to the talented (sarcasm) developers of sochi2014.com! Well, on the outside the website looks okay, but on the inside, oh brother, give me a break! I’ll point out the most interesting and fun ones:

  • Starting from the first line: no document type definition
  • I noticed an empty table with a cellpadding=3, is that the new standard for margins? ;)
  • Check out the script type=”” language=”javascript”, what the hell does that mean?
  • Wow,   heh, haven’t seen that for a while!
  • Cool, they’re replacing margin-top: 1px; with an empty.gif height=1 image!
  • Closer to the bottom of the page, I found 11 closing divs right next to eachother.. I don’t believe that they’re using a minify script for that one
  • And ~ 50 errors according to the W3C HTML validator, I don’t think there’s a reason to mention them all

That’s probably enough for a start. Very frustrating when a website like that is being built like *that*, and with a page rank of 8! I’d give those guys a solid 2 ;)

Now, back to Facebook. I registered a new application, did some setup and managed to get a four-page website, similar to sochi2014.com, inside apps.facebook.com, with a few modifications (and cleaning up of the code), including a dashboard and a tabs widget for navigation. This was quite straightforward and simple to do (take a look at the Facebook API Developers Guide), the linking structure was okay, the contact form was done in only a few seconds (thank you Facebook for your great FBML!) and the static pages were simply some copy-pasting.

Once I got that up and running I decided to port it into the fan page (as an application tab) that Tim and I manage. I was quite surprised that all the linking structure died, but was pleased that I could at least see the front page, besides the fact that you have to click on the flash element before it’s shown. With a few more experiments and some help from the Facebook Platform Developer Forum (which is a very sweet place btw) I came to a conclusion that multipaging will not work in application tabs on profiles and fan pages. The easiest way around this is of course to use FBJS (javascript) to imitate multiple pages by hiding and showing certain elements on mouse click events. Forms would be a problem too, unless submitted via Mock AJAX.

Tim then asked me if I could move the menu I built up to the top where the main tabs are (Info, Wall, Photos, etc) which seemed impossible. Well, at least from within one Facebook application. So if I’d like to have 5 tabs at the top of the fan page I’d have to register 5 new Facebook applications, what a mess! Wouldn’t it be easier to manage a certain amount of tabs within one application and let profile owners and fan page administrators decide which ones they’re going to put up their navigation? Oh well.

It’s very strange though why companies aren’t yet taking full advantage of what fan pages might look (and work) like. Let’s take a look at Mashable’s Killer Facebook Fan Pages. Out of the 5 pages featured there, the Redbull Fan Page is the one I liked most. They have FBJS pagination, flash video and links to their application page which is quite interesting (yet still a single page with minumum user interaction). The Adidas Originals custom fan page is fully based on Flash, which is why they ask you to “Click to Enter” before you could see anything. The Starbucks and Coca-Cola pages are less interesting, simple HTML with links to external pages. The Pringles fan page doesn’t even have an app of it’s own – Killer?

Here are a few other pages worth checking out. Smashing Magazine – they’ve got two sections: “The Smashing Book” and “Write for Us”, which are two different Facebook applications (judged by the URL). The BMW Fan Page features an interactive form with FBJS validation and submission – way to go guys! And I’m pretty sure there are tonnes of others which I didn’t come across.

Facebook API Experiments: Twitter Tags

For quite some time now I’ve been dreaming about getting into the Facebook Platform (API, Markup Language, etc) but haven’t had good enough reasons to do so. One good friend of mine Timothy gave me those reasons not so long ago and guess what! I came up with my very first Facebook App! It’s still in the sandbox, don’t rush searching for it in the applications database. I’m not going to share any code as it’s all clumsy but I do want to share some screenshots and my first experience with the Facebook API.

One very interesting thing about the API is the testing console, where you could run any Facebook API methods, very useful for debugging. Interface design is very catchy too, with the new Facebook Markup Language and the FBML testing console, so quick and robust! Pepole are still asking for form elements extensions though, such as the checkbox or option – it seems that they come out buggy as fb:editor-custom.

Anyways, the first thing that came into my mind is adding a Twitter Tags tab to a profile or fan page, so I used the Foller.me API and within a few hours I managed to get a fully working (or not) canvas application tab. I’m surprised by how well-written the Facebook PHP Client Library is. All the methods are explained in the code comments and do exactly what they’re expected to. The Facebook Markup Language takes care of application settings, private areas (app configuration, etc) and everything else. The overall Facebook Developers Documentation is okay, I’ll give that an 8 out of 10 and I like them running the MediaWiki software ;) Here are some screenshots of my application:

Still not sure where this is going but Timothy had some great ideas about custom Facebook Apps. I guess a release of the Twitter Tags application would be handy for some profiles (or at least for some more experience), so I might push that forward in the near future and file an “add to facebook database” request to go public. After that we’ll aim for something bigger.