Thursday, 26 February 2009

Battling the Facebook API

One of the things I've been trying to do with Google App Engine is get my app to talk to Facebook. As it turns out, this is a reasonably straightforward task made incredibly complicated by the appalling Facebook Developers documentation. Just trying to work out what it is you need to do (never mind how you actually go about doing it) is a real trial.

Undeterred (I was getting paid for this, after all) I persevered and eventually worked out that before my app could talk to Facebook, users would have to add it to their profile and grant it permission to do stuff - for this I would need a 'Callback URL'. Unfortunately, all the examples in the docs are PHP, but here's what I came up with in Google App Engine:
class FacebookPage(webapp.RequestHandler):

def get(self):
self.post()

def post(self):
self.response.out.write("<fb:prompt-permission perms=\"status_update\">\
Grant permission for status updates\
</fb:prompt-permission>")
Yes, it's not pretty and yes, I've got markup in the source code, but it works. Those three lines of FBML (Facebook Markup Language) request that the user gives my app the necessary permissions. Once added, my app can then use the PyFacebook utility to make calls to the API:
fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
result = fb.users.setStatus(new_status, False, uid=facebook_user_id)
Easy when you know how!

No comments: