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!

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

2 comments