Sometimes you just want to write a little script using Facebook’s api that updates your status, or downloads all your photos, or deletes all those empty albums you accidentally created. In order to streamline my writing of one-off facebook scripts, I created a micro api client that implements the client-side authentication flow and has a few utility functions for accessing the graph api and fql.
To use this mini api client, all you have to do is put 4 lines of code at the top of your python script:
Once authenticated, you can make whatever calls to the graph api or fql that you want. For example:
Post a status update
The code is just in a gist on github at https://gist.github.com/1194123. Feel free to comment on this post or on the gist if you have questions.
To use this mini api client, all you have to do is put 4 lines of code at the top of your python script:
from urllib import urlretrieve import imp urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py') fb = imp.load_source('fb', '.fbconsole.py')Now you can specify the permissions you’ll need for your script (from the list of available api permissions) and authenticate yourself:
fb.AUTH_SCOPE = ['publish_stream'] fb.authenticate()By default, the api client makes requests as the “fbconsole” app. You can use your own app by setting
fb.APP_ID
. When you authenticate, a browser window will open asking for whatever permissions were requested by your script. After you go through the permission dialog, the script will continue running. The access token used is stored in a local file when you authenticate so the next time around you won’t be presented with a dialog in your browser.Once authenticated, you can make whatever calls to the graph api or fql that you want. For example:
Post a status update
status = fb.graph_post("/me/feed", {"message":"Hello from my awesome script"})Fetch likes on a status update
likes = fb.graph("/"+status["id"]+"/likes")Delete a status update
fb.graph_delete("/"+status["id"])Upload a photo (why does python make this so hard?)
fb.graph_post("/me/photos", {"message":"My photo", "source":open("my-photo.jpg")})Query FQL tables
friends = fb.fql("SELECT name FROM user WHERE uid IN " "(SELECT uid2 FROM friend WHERE uid1 = me())")If you download https://raw.github.com/gist/1194123/fbconsole.py and run it, you’ll be dropped into a python shell so you can just play around with api calls in an interactive environment. An IPython shell will be used if you have IPython installed.
The code is just in a gist on github at https://gist.github.com/1194123. Feel free to comment on this post or on the gist if you have questions.
No comments:
Post a Comment