Saturday, September 21, 2013

Connect to facebook Graph API with python

Yes, this type of posts are all over the world wide web. However, there are thousands of methods and not all of them are going to work for you. I've tried to find the easiest way to interact with Graph API and that's what I'm going to describe, along with the problems I've faced throughout the process. I've been using PyDev in Eclipse.

1. Get python-facebook sdk. this seems to be the official one. Install it with this command
sudo pip install git+git://github.com/pythonforfacebook/facebook-sdk.git

2. If you have opened up eclipse before this process, you are going to get an import error. PyDev doesn't refresh the PYTHONPATH automatically. You have to got to

File > Properties > Edit the launch configuration > Refresh tab > Check refresh all resources

3. Now, you would need an access token to interact with the Graph API. Usually this is done with a browser requesting with app id and secret token and then facebook returns an access token. That's a bit tricky, I was looking for an easier method. However, for testing purpose, facebook also gives access tokens directly.
Go to this link : https://developers.facebook.com/tools/explorer and click on generate access token. It shall ask for the permissions you want to have in your application and then generate an access token for you. However, It's temporary and shouldn't be hard coded in your application forever.

4. Paste the following code in your editor. Among tons of others, I've found this one little and easy.
import facebook
token = 'your secret token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

And see the output in console, a nice list of your friends. Remember two points:

  1. If it fails to find 'facebook' module, you might need to restart eclipse.
  2. If it fails to find Graph API, re-install facebook module. You can remove it by issuing
    pip freeze
    to get the actual python-facebook module name and then
    pip uninstall that-module