Python and Twitter

I’m a user of Twitter, and my favorite part of the Twitter experience is the API. Twitter has allowed users access to a simple, yet expansive API that has spawned a whole community of users that create apps, bots, mash-ups etc. using Twitter.

I figured I’d write a little Python wrapper to work with the Twitter API. For some reason, I didn’t do any research, and only very recently found python-twitter. I’m not upset I spent the time—I actually like my implementation because it’s so light. Here it is:

import base64, httplib, urllib

class TwitterAPI:   
    def __init__(self, username, password):
        # generate authentication header string
        self.authentication = { "Authorization": "Basic %s" 
            % base64.encodestring("%s:%s" % (username, password)).strip() }

        # create connection
        self.connection = httplib.HTTPConnection("twitter.com", 80)

    def update_status(self, status):
        # send post response with authenticated status
        self.connection.request("POST", "/statuses/update.xml",
            urllib.urlencode({ "status": status }), self.authentication)
        response = self.connection.getresponse()
        return response.status

It’s pretty simple—I’ve written out update_status which, surprisingly, updates the status of the authenticated user. To use the other API functions, just adjust self.connection.request accordingly. For example, to fetch the public timeline:

def get_public_timeline(self):
    # send get response--no authentication needed
    self.connection.request("GET", "/statuses/public_timeline.xml")
    response = self.connection.getresponse()
    return response.read()

response.read() just spits out the request (which we have asked for in XML form) in it’s entirety. Use your favorite method of parsing XML in Python—alternatively, you may opt to return any of the other supported formats. A few things to point out. Notice how self.connection.request is now passed a GET parameter rather than POST—this is defined in the API and is function-specific. I didn’t need to send any further information because Twitter doesn’t require it. update_statushowever, did: status. To send a direct message, for example, you need to provide user and text for the recipient.

Simple and easy. Feel free to use and abuse this. Credit would be appreciated—or, buy me something nice.

—★—

« Ode to Em-dash | Python Decorators: Syntactic Sugar »