How to Get Started with the Twitter API

Kevin and Gary show at FOWA London

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.

Screenshot of We Love Typography's listing of tweets containing the hashtag #WLT
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!

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from HTML, CSS or WordPress.

Start Learning

Treehouse

Our mission is to bring affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world.

Comments

35 comments on “How to Get Started with the Twitter API

  1. @David

    Here’s an excerpt from the API docs:
    The REST API does account- and IP-based rate limiting. Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment.

    The 150 requests per hour is the default, but you can contact Twitter and ask if they’ll relax that limit for you.

    Searches don’t have that kind of limitations in place, and judging by the huge amounts of traffic we get at We Love Typography, there’s very little chance of hitting the limit with search.

    Since I’m not getting that error message here in Finland, I’m guessing that the IP-based rate limiting is in effect.

    You can always use your own username (or just pick one at random) for those examples.

  2. Nice tutorial. If I want to use this on a wordpress page, where do I host the class.twitter.php file? Tried it in various places but the page fails to load the moment that file is called. (Same with time_passed.php I suppose)

    Thanks.

  3. The script assumes you’re calling it from a file inside the same directory as class.twitter.php and time_passed.php.

    You can use to get your current working directory. Just make sure those paths in the require_once calls are relative to that path.

  4. Sorry about that, it seems you can’t use PHP tags here…

    Correction: you can use <?php echo getcwd(); ?&gt to get your current working directory.

  5. Pingback: 21 fresh links for you! « Adrian Zyzik’s Weblog

  6. Pingback: David Rios (dfrios) 's status on Thursday, 20-Aug-09 15:16:30 UTC - Identi.ca

  7. Pingback: How to Get Started with the Twitter API | Switch on the Code

  8. Great Article!

    I was wondering if there was a way to get the number of followers particular users have using the Twitter API? Is that possible?

    Cheers

    • Sure it is. The response in the user_timeline example already has that information:
      $d->user->followers_count

  9. Pingback: Daily Digest for August 21st | piersonthe.net

  10. Pingback: links for 2009-08-22 « sySolution

  11. Pingback: Daily Digest for August 22nd | piersonthe.net

  12. Pingback: Working With the Twitter App | CssGalleries

  13. Thanks for the info! Can I limit the number of tweets pulled out or do I have to clip it in the foreach()? It would be nice to cap it from the getgo.

  14. Pingback: social media articles august 16th – august 31st 2009, twitter, facebook, etc « Stefanm, my link collection

  15. Pingback: 10 Twitter API Tutorials. « The Domage

  16. Thanks for the article, works great. I have a question. Is there a way to make website links active instead of just text in the displayed results of someone’s twitter?

    Thanks.

  17. I would love to use something like this to output hashtag searches with cache and pagination. Is there any add-on tutorial for adding these functionalities?

    Thanks :)

  18. i want to use twitter API for my site.Please tel me how to get started with it?how to get twitter API and use it in my application?i have got a php-twitter 1.1 zip which contain the twitter class .please tel me how to use it?plz send the anxswer on my id,if possible.
    Regards,
    Sarita

  19. Nice tutorial, been looking for something that is all php based so that I can cache it on my site in case twitter goes down, and to the numbnuts above, he just did tell you how to get started…

  20. How does one modify the parameters in the search query, i’ve noticed that what works in the url does not work here, so if i wanted to do a since or a results per page i cannot do so. Example: $data = $s->search(‘from:tuaw&phrase=iphone&rpp=15′);

  21. Twitter API documentation is missing a clear wording of what is being counted as part of the query length.

  22. i want to use twitter API for my site.Please tel me how to get started with it?how to get twitter API and use it in my application?

  23. Nice tutorial and I got it working just fine except for one thing. The tweets are 2 hours behind… So tweets posted @ 20:00h are displayed as if they were posted @ 18:00h. Must be something simple??

    I hope you can help!