March 31, 2009

Interfacing with Twitter

By Gian Zas

twitter_birdTweet tweet tweet! All the farm is chating about Twitter, all the farm is using twitter and all the farm is building applications on top of it.

Luckily, Twitter seems to be a programmer’s best friend, why? you may be asking… because of its wonderful API. Well designed and documented, what else could you wish?

The Twitter API is RESTful, but it doesn’t only mean that you can access to it over HTTP, sending parameters in GET or POST requests, it also means that it is designed complying with the principles of REST. A plus to this API is that it supports JSON, XML, RSS and Atom data formats and user authentication is reached by Basic Auth.

Due to the popularity of the service, a bunch of libraries have been developed and are heavily used to interact with Twitter, but if you like to explore the other end of the telephone line you are reading the right post ;). As we’ve said the API is accessible through HTTP, so let’s go and fire up your browser and point to:

Ok, what do you see? the last tweets of the user whose screen name is twitterapi formatted in xml. Another popular operation is:

That url returns (after successful authentication) the latest tweets posted by the authenticated user and it’s friends.

Because requesting a URL and satisfying basic authentication mechanisms are easy tasks in the day-to-day programming languages, invoking the API is a piece of cake. As Python has been one of our favorite languages, we’ll show you how to retrieve user statuses and post a new one. Here we go!

First we must declare the necessary imports (simplejson must be downloaded and installed before) and declare the URLs to be accessed.

get_statuses retrieves the last tweets of #{screen_name}, it simply adds the screen_name parameter to the url, then requests it and finally parse the response using the json library. To print the tweets retrieved in a simple manner:

To post a tweet we simply do a POST request to the UPDATE_STATUS_URL passing the status (the tweet’s text) parameter.

Username and password corresponds to the twitter user (you for example) whose status will be updated, obviously the user (ex: you again) must have a twitter account.

Because the API uses basic authentication we call to the __authenticate function:

For a good explanation on how this chunk of code works, please refer to  this great tutorial

As you’ve seen, in a small amount of code we are interacting with Twitter, where to use it, how to display the results and what ideas bring
to life is up to you!