LearnHow 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:

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:

<?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 } ?>

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.

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:

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;
<?php foreach($data as $d){ ?>
<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); ?>
<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); ?>
<?php } ?>

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!

35 Responses to “How to Get Started with the Twitter API”

  1. thank you very much =)

  2. pLot Developers on January 31, 2011 at 11:56 pm said:


  3. It’s pretty useful.


  4. Shripad Bharde on September 10, 2010 at 12:48 pm said:

    It is working nicely. Thanks for your tutorial.

    Shripad Bharde

  5. Matthijs on May 19, 2010 at 7:28 pm said:

    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!

  6. 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?

  7. snorkeling equipments on November 16, 2009 at 12:30 am said:

    great info and thanks for sharing

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

  9. 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’);

  10. 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…

  11. Sarita Sharma on September 29, 2009 at 11:19 am said:

    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.

  12. 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 🙂

  13. Mike Brisk on September 11, 2009 at 3:00 pm said:

    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?


  14. 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.

  15. Zenhobo on August 26, 2009 at 6:11 pm said:

    nice work i will try twitter API inside my blog..thanks

  16. Great Blog post. I am going to bookmark and read more often. I love the Blog template.

  17. 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?


    • Kari Pätilä on August 21, 2009 at 5:50 am said:

      Sure it is. The response in the user_timeline example already has that information:

  18. Antonio Lupetti on August 20, 2009 at 12:01 pm said:

    Nice tutorial. I wrote a similar post some time ago about how to implement a stream of tweets Monitter-like with PHP and jQuery:


  19. Kari Pätilä on August 20, 2009 at 9:05 am said:

    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.

  20. Kari Pätilä on August 20, 2009 at 9:03 am said:

    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.

  21. 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)


  22. Kari Pätilä on August 20, 2009 at 8:19 am said:


    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.

  23. The XML URL: http://twitter.com/statuses/user_timeline/karipatila.xml currently indicates that only 150 requests per hour can be made and stops serving data.

    Is this a limitation of embedding content into your own site and calling data in this way?

  24. Oscar Burgin on August 20, 2009 at 7:57 am said:

    nice work. I love this article.

Leave a Reply

Learn to code with Treehouse

Start your 7 day free trial today and get access to hundreds of video courses in web development, design and business!

Learn more