How to Get Started with the Twitter API
By Kari Pätilä
20 August 2009 | Category: Code
Thanks to some very nice open source libraries for quite a few programming languages, interacting with the Twitter API has become exceedingly simple. In this article we'll be looking at different ways to pull in data from Twitter.
The libraries page of Twitter’s API wiki is a good place to start. For these examples I’m going to use the php-twitter class, but I’ll include the requests and responses so this doesn’t turn out to be all PHP. After all, the API itself doesn’t care which language I’m using.
The php-twitter zip archive contains some nested folders and finally a file: class.twitter.php. You’ll eventually get to it, so keep opening those folders!
Getting your timeline from Twitter
With this library you don’t have to worry about data exchange formats (the default is JSON), but if you’re still stuck with PHP 4, you might have to set the $type variable to ‘xml’. But, let’s face it: if you enjoy XML you’re kind of insane, aren’t you? If your host is still using PHP 4, chances are that they’ll update you to the latest version if you ask them nicely.
The API method we’ll be using is user_timeline. You can check out the output by pointing your browser to http://twitter.com/statuses/user_timeline/karipatila.xml. Notice the “.xml” — that’s the data exchange format. You can use “json”, “rss” or “atom” there as well. That URL is the GET request the API is responding to, which could be made using any programming language.
So, using the library, this is all we need to fetch my timeline:
<?php
header('Content-type: text/html; charset=utf-8');
require_once 'class.twitter.php';
$t = new twitter;
$data = $t->userTimeline('karipatila');
?>
First we make sure the script can handle unicode characters and then we include class.twitter.php. Next we’ll set up a new instance of the php-twitter class, which can be used to pull in some data.
The script loads the timeline from Twitter and stores it into the $data variable. Along with some user information it contains the tweets themselves, which are what we’re really interested in. Let’s take a look at what kind of information we’re getting. This is one of my tweets in the $data array:
[truncated] =>
[text] => TomTom Nordic, 69,90€: http://bit.ly/wX51t (App Store link) - wonder how expensive the car kit is?
[in_reply_to_status_id] =>
[created_at] => Mon Aug 17 07:55:51 +0000 2009
[favorited] =>
[in_reply_to_user_id] =>
[id] => 3358348095
[in_reply_to_screen_name] =>
[source] => <a href="http://www.atebits.com/" rel="nofollow">Tweetie</a>
We can use that information to make a script that lists my recent tweets. The API method statuses user_timeline returns the 20 most recent statuses posted from the authenticating user. I also wanted to link back to the accounts that are being replied to, so I’m looking for an @ symbol followed by one or more word characters and linking them to their respective Twitter profiles:
<ul>
<?php foreach($data as $d){ ?>
<li><?php echo preg_replace('/(^|\s)@(\w+)/','\1<a href="http://twitter.com/\2">@\2</a>', $d->text); ?></li>
<?php } ?>
</ul>
A short note on rate limitations; caching the output from this script will become necessary sooner or later. The technical details are beyond the scope of this article, but you might want to consider saving the output into a database or a file and checking for updates every couple of minutes or so. A limit of 150 requests per hour applies to the REST API.
Get the source for fetching a user’s timeline here.
Let’s look for treasure
For example, let’s do a search for the hashtag “#carsonified”. They have recently announced Hello App, so there should be some chatter around that subject. We can add terms to the search like this:
$data = $s->search('#carsonified OR #HelloApp');
The search API method requires the query to be URL encoded, so we replace # with %23 in the request: http://search.twitter.com/search.json?q=%23carsonified&rpp=5&page=1. The search API accepts either “json” or “atom” as the exchange format.
If we break that request down, we find it contains the following information:
q=[query string]
rpp=[results per page]
page=[page number]
The search API has virtually no rate limits, so you don’t have to worry about your app getting throttled. Note that this time we’re also creating another instance with
$s = new summize;
which refers to the search class found in the php-twitter library.
<?php
header('Content-type: text/html; charset=utf-8');
require_once 'class.twitter.php';
$t = new twitter;
$s = new summize;
$data = $s->search('#carsonified');
$data = $data->results;
?>
In this example one tweet stored in $data might contain the following information:
[text] => Just trying out Matt by #carsonified. uniquely designed site with workable UI.
[to_user_id] =>
[from_user] => _midnightshad
[id] => 3284756132
[from_user_id] => 2270963
[iso_language_code] => en
[source] => <a href="http://themattinator.com" rel="nofollow">Matt</a>
[profile_image_url] => http://a1.twimg.com/profile_images/60040548/panda_normal.jpg
[created_at] => Thu, 13 Aug 2009 11:50:01 +0000
We can use this to make a simple listing based on the results:
<?php
header('Content-type: text/html; charset=utf-8');
require_once 'class.twitter.php';
$t = new twitter;
$s = new summize;
$data = $s->search('#carsonified');
$data = $data->results;
?>
<ul>
<?php foreach($data as $d){ ?>
<li>
<img src="<?php echo $d->profile_image_url; ?>" alt="" />
<?php echo preg_replace('/(^|\s)@(\w+)/','\1<a href="http://twitter.com/\2">@\2</a>', $d->text); ?>
<em>by</em>
<a href="http://twitter.com/<?php echo $d->from_user; ?>"><?php echo $d->from_user; ?></a>
<?php echo $d->created_at; ?> <em>from</em>
<?php echo html_entity_decode($d->source); ?>
</li>
<?php } ?>
</ul>
This script outputs the tweets containing the word #carsonified along with profile images, timestamps and links to the client used.

We Love Typography uses similar formatting to pull in tweets with the hashtag #WLT.
In the following source file I’m using a function for formatting the created_at field, so instead of “Fri, 14 Aug 2009 14:24:58 +0000″ you will get something like “3 days, 17 hours ago”.
Get the source for searching Twitter here. You’ll also need the file with the time_passed function for this one.
When the library just isn’t good enough
The search API returns 50 results by default, which might not be convenient for everyone. The class php-twitter doesn’t set the results per page variable in the query strings, so let’s add that. You need to open the class.twitter.php file and replace line 844 with this:
function search( $terms=false, $rpp=false, $page=1, $callback=false )
Finally we add these three lines starting from line 854:
if( $rpp )
$qs[] = 'rpp=' . $rpp;
$qs[] = 'page=' . $page;
After these changes:
$data = $s->search('#carsonified', 5);
would only return the five latest results, and it would set the pagination to page one, whereas
$data = $s->search('#carsonified', 5, 2);
would set it to start from page two.
Know your API
The API Documentation is pretty well done, so make sure to read it. Check out the methods like searching for current or daily trends or listing your followers and go make the next big Twitter app!
Follow @thinkvitamin on Twitter Please check out Treehouse

