Accessing Twitter’s API through Python

Posted:

If I understand the Internet correctly, the new hottness for doing oauth stuff in Python is this oauth2 library. This twitter doc is a little out of date, so here’s my version of it.

import oauth2 as oauth
from pprint import pprint
import json

def req (url=None,
         http_method="GET",
         post_body='',
         http_headers='',
         key='',
         secret=''
         ) :
    con = oauth.Consumer(key='ConsumerKey'
                         secret='ConsumerSecret')
    token = oauth.Token(key=key,
                        secret=secret)
    client = oauth.Client(con, token)
    res, content = client.request(
        url,
        method=http_method,
        body=post_body,
        headers=http_headers,
        )

    return content

c = req(url="http://api.twitter.com/1/statuses/home_timeline.json",
        key='AccessToken',
        secret='TokenSecret')

if len(c) > 0 :
    pprint(json.loads(c))

You get the consumer key and secret by registering an app on Dev.twitter.com. The Access Token and Token Secret come either from dev.twitter.com (for debugging only) or through the oauth login process by which a request token is exchanged for the access token and token secret.

Note that client.request() performs HMAC_SHA1() signing of the paramters. It looks like if you pass in post_body, the parameters will be parsed and signed too. Still, it is weird that this method doesn’t simply take a dictionary object for parameters.

The real difference is how the library is included. Confusingly, the script in the examples directory of this library does not correctly include itself (the project was forked and not all the cruft was cleaned up :-)