Basics of using Twitter’s API
Note: this tutorial was originally intended to be posted on Nettuts, they originally accepted it but then realized it relies on an existing PHP library – they prefer if you do that sorta stuff from scratch so fair enough. Anyway I know it’s a bit different from my usual content but no point letting it go to waste!
Integrating with Twitter’s API using OAuth
Making your web application work with Twitter is one thing, but using OAuth for a secure login looks more professional and makes your users feel more safe, a priority in todays web application design. Today we look at making a simple application that utilizes Twitter’s API that you can use in your own applications.
A Little OAuth Background
Before we begin, we need to know a little about what OAuth is and how it works. OAuth is an authentication protocol, in our case it allows users to give us access to their account without giving us their password. In short, we send the user to Twitter where they can choose to ‘Allow’ or ‘Deny’ our applications request to access their account, if the user chooses to Accept then Twitter sends our application a ‘token’ that we can use to access the users account. In total, we deal with 4 tokens.
- Request Token – Twitter will give you this token before you send them to authenticate. If the user chooses to approve your application, we get an access token which allows us to access the users account. We can get the access token again at a later date using the request token and the request token secret key.
- Request Token Secret – When you receive a request token, you also receive a request token secret. Consider that the request token is your applications username for Twitter to identify your app, and the request token secret is the applications password. You will also need to pass this token to get an access token.
- Access Token – After we send the user to Twitter to authenticate with our request token and our request token secret, if the user approves our application we receive an access token and an access token secret to use the API on the users behalf. Currently access tokens and access token secrets do not expire and are only invalid if a user chooses to remove your application from their connections tab. Once you have the access token and access token secret you send them to the API along with any command you wish to run.
- Access Token Secret – Similar to the request token secret, consider this the password for the access token that must also be passed when making an API call.
Whew, that was quite a lot to take in, but it’ll all become clear soon. One more (or two more) things we also have to include in our application are key’s. There are two key’s which we must use before we can even get a request token, and they are;
- Consumer Key – Needed to get a request token and request token secret, you get this key when you create your application on Twitter.
- Consumer Key Secret – The password part to the consumer key.
Now we’ve covered the minimal amount of OAuth material we need to start, let’s jump right in and start creating our application.
Step 1
First of all, we need to let Twitter know that we’re setting up an application. To do this we simply visit http://www.twitter.com/oauth_clients and click ‘Register a new Application’.

Configure your application to roughly the same, changing the callback URL to where you’re going to put the PHP file we’ll create today. The first five fields are quite self explanatory. Application type is used to distinguish whether our Twitter app will run as a desktop program or a web application, ticking browser let’s Twitter know we’re on the web. Callback URL is where Twitter will send the user (along with those all important access token’s) after they’ve authenticated. Default Access type defines whether we’ll just be pulling information, or whether we’ll be pushing it too, things like changing status or profile information.
The final field, Use Twitter for login is an interesting one. When creating a web application or website based around Twitter, there are two options regarding how to handle your users. The first option is to create your own user system, and then have them authenticate with Twitter, tying the two accounts together. The second option allows your users to simply authenticate with Twitter and use your site like an extension to Twitter.com – where if they are logged on to Twitter, they can use your app seamlessly.
Once we’re happy with all of this, we should get something like this;

Great, now we have our very own consumer key and consumer key secret, the URL’s we can safely ignore for now. Keep this page open as we’ll need those two token’s very soon.
Step 2
Now we’ve let Twitter know that we intend to create an application using those two key’s, we can start working on the PHP – first let’s create our files. Our application will consist of two of our own PHP files, but it will require two others. The first file we will require will be the OAuth PHP library, the second is a custom class written for using OAuth with Twitter, created by Abraham Williams. You can download the two required files in the download button at the bottom of this tutorial, or from here, the two files we need are OAuth.php and twitterOAuth.php
Once you’ve got two files, paste the two required files into a folder called inc, then make two files above them called twitter.php and send.php, you should have a structure that resembles this;

Step 3
Yay, now we can start the fun part and start slapping some code in. Let’s fire up send.php and start laying out our file. This file is our send to Twitter file, so this is where the user lands directly before jumping to Twitter. First of all we need to create some simple variables we’ll need and establish/call a few things.
<?php
// Twitter API Example
//
// Nettuts
session_start();
require_once('inc/twitterOAuth.php');
// make sure you swap these for your own!
$consumer_key = 'r2IJMwUCShWm7DsJfdO9rg';
$consumer_secret = 'nFyEMUG2wlNOYE628iGXyUDrvUGcezQvyE7nssqREs';
// create some request tokens
$toa = new TwitterOAuth($consumer_key, $consumer_secret);
$tokens = $toa->getRequestToken();
?>
Line by line; we first of all establish our session with session_start – that’s pretty self explanatory. Then we call the Twitter OAuth library, you’ll notice that we don’t call the OAuth.php file, that’s because twitterOAuth.php does it already. The next couple of lines simply hold our consumer key and consumer secret that Twitter gave us when we created our application
Next we create an object called $toa passing to it, our consumer key and consumer secret. With these two key’s, we can generate a request token and a request token secret. The next line tells the twitterOAuth object to create the request token’s and store them in the $tokens variable where we can access them.
Now we’ve generated the request tokens, we need to store them in our session and send the user to Twitter to authenticate, to do this we put the request token and request token secret in to our session, along with a variable that keeps track of where in the process we are. Place this code at the bottom of the file.
// store it in our session
$_SESSION['oauth_request_token'] = $tokens['oauth_token'];
$_SESSION['oauth_request_token_secret'] = $tokens['oauth_token_secret'];
$_SESSION['oauth_state'] = 'SENT';
// send the user on their way
header('Location: '.$toa->getAuthorizeURL($tokens['oauth_token']));
Step 4
Digging a little deeper, we now have the ability to send people to twitter along with a request token, if they approve our application then hopefully we should get some of those delicious access tokens and start playing with the juicy API.
When a user comes back from Twitter we could do numerous checks, such as the referrer, to see if they’re heading home from Twitter to our web app, however if successful then Twitter will use our callback URL with a $_GET variable called oauth_token. So since we sent them to Twitter with the state ‘SENT‘, all we have to do is check that the state matches ‘SENT‘ and the $_GET['oauth_token'] is set. Let’s put this in to code form. Fire up our main file, twitter.php and put the following;
<?php
// Twitter API Example
//
// Nettuts
session_start();
require_once('inc/twitterOAuth.php');
// make sure you swap these for your own!
$consumer_key = 'r2IJMwUCShWm7DsJfdO9rg';
$consumer_secret = 'nFyEMUG2wlNOYE628iGXyUDrvUGcezQvyE7nssqREs';
if ( $_SESSION['oauth_state'] == 'SENT' && !empty($_GET['oauth_token']) )
{
// the user has returned from Twitter
$_SESSION['oauth_state'] = 'RETURNED';
}
?>
<html>
<head>
<title>Nettuts Twitter Example</title>
</head>
<body>
<?php
if ( !empty($info['screen_name']) )
{?>
Hey there <?php echo $info['screen_name']; ?>, looks like you've successfully authenticated!<br />
<a href="http://www.YOURSITE.com/twitter.php?clearsession=true">Click here</a> to start again!
<?php } else { ?>
Hey there, <a href="http://www.YOURSITE.com/send.php">Click here</a> to sign in with Twitter!
<?php } ?>
</body>
</html>
That’s quite a chunk of code. You’ll recognize the top of the file as it’s the same as send.php, we establish the session and call the twitterOAuth class, then we set the consumer key and consumer secret (remember to change these to your own!).
Next we check to see if the user has been sent to twitter AND they have an oauth_token which means they’ve returned. If they have we set their session state to returned so we know that they’re back and it’s time to get that access token and access token secret. Below the script we have a (very) simple HTML page that when logged in will let the user clear the session, and when not logged in will offer the user a link to send.php
First of all we need to make that clear session link work, we can do that by changing our if statement to look like this;
if ( $_GET['clearsession'] == 'true' )
{
session_destroy();
} elseif ( $_SESSION['oauth_state'] == 'SENT' && !empty($_GET['oauth_token']) ) {
// the user has returned from Twitter
$_SESSION['oauth_state'] = 'RETURNED';
}
Now if a user clicks the reset session link, we clear the session and we can start again. If you visit your page in a browser right now it should look like this;

Ok so now we can send the user to Twitter with a request token, if they return with an access token we have a place to put our code and we can clear our sessions. Now we’re going to get our access token’s so we can start accessing the API.
Step 5
Where we set our oauth_state to ‘RETURNED‘, underneath that line let’s start coding. To get the access token’s is pretty simple, we’re going to create an object from the twitterOAuth class again, but this time with 4 arguments, we now pass it our consumer key and consumer secret, but we also pass it our request token and request token secret. Twitter will check our consumer key’s and request token’s and then send us the access token that corresponds with the request token we sent. Our new if statement looks like this;
if ( $_GET['clearsession'] == 'true' )
{
session_destroy();
} elseif ( $_SESSION['oauth_state'] == 'SENT' && !empty($_GET['oauth_token']) ) {
// the user has returned from Twitter
$_SESSION['oauth_state'] = 'RETURNED';
// generate our access tokens
$toa = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
$tokens = $toa->getAccessToken();
// store tokens in session
$_SESSION['oauth_access_token'] = $tokens['oauth_token'];
$_SESSION['oauth_access_token_secret'] = $tokens['oauth_token_secret'];
// just here is where you could store the tokens
// in a database for future use
}
if ( $_SESSION['oauth_state'] == 'RETURNED' )
{
$toa = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
// now we can do some cool stuff
$info = json_decode($toa->OAuthRequest('https://twitter.com/account/verify_credentials.json', array(), 'GET'), true);
}
Hooray, if everything went according to plan we should now have access token’s. You’ll notice the two-line comment, that’s where you could insert the access token and access token secret in to a database for future use. The reason we do the cool stuff in its own if statement is because the first if statement only fires when the user hasn’t yet authenticated
OAuth access token’s can be set to expire for other services, however for Twitter they never expire (or at least, yet).
Step 6
Now we’re in, let’s do something. When requesting data from Twitter, we can request it in two formats, JSON or XML. To change format we simply change the extension of the URL in the authorized request function.
// Here's a JSON request
$info = $toa->OAuthRequest('https://twitter.com/account/verify_credentials.json', array(), 'GET');
// Here's an XML request
$info = $toa->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
Personally I use the JSON request, but feel free to use which ever you prefer.
If we used the JSON request, it would pull all of the users credentials but in JSON format (obviously). Alternatively we can parse them in to a nice associative array using the function json_decode();, by setting the second parameter to true we get a lovely array. Using a little wrapping, our code to pull the users profile into an array looks like this;
$info = json_decode($toa->OAuthRequest('https://twitter.com/account/verify_credentials.json', array(), 'GET'), true);
Now when you hit send.php and go to Twitter, then return with an access token, you should see something like this;

Wrapping Up
There you have it, you can now have users authenticate using Twitter then read their profile, make them tweet, it’s up to you!
If we use print_r($info) we can see all the information returned using the verify_credentials.json request
Array
(
[notifications] =>
[description] => Self-proclaimed web development and blogging genius
[utc_offset] => 0
[profile_sidebar_border_color] => 181A1E
[followers_count] => 28
[friends_count] => 6
[profile_text_color] => 666666
[url] => http://www.dans-blog.com
[name] => Dan Walker
[statuses_count] => 37
[profile_background_image_url] => http://s3.amazonaws.com/twitter_production/profile_background_images/4970623/wood-bg.jpg
[created_at] => Mon Feb 23 17:24:53 +0000 2009
[protected] =>
[status] => Array
(
[in_reply_to_screen_name] =>
[text] => Hey Nettuts!
[truncated] =>
[in_reply_to_status_id] =>
[created_at] => Tue Jun 16 09:47:54 +0000 2009
[in_reply_to_user_id] =>
[favorited] =>
[id] => 2190461946
[source] => web
)
[time_zone] => London
[favourites_count] => 0
[profile_link_color] => a50f30
[profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/84820352/eb0142f7216e4e0e71d6857a685b760f_normal.png
[profile_background_tile] => 1
[profile_background_color] => 1A1B1F
[screen_name] => iDemonix
[following] =>
[location] => England
[id] => 21671131
[verified_profile] =>
[profile_sidebar_fill_color] => 252429
)
You can get a whole host of information from this request, you could do some pretty cool stuff, like styling your site similar to the users Twitter settings, get a thumbnail of the users website – the world is your lobster/oister/tweety-pie.
For those who want a few more commands, here’s a couple of requests you can experiment with;
// make the user tweet
$info = $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => 'Nettuts made a great post on the Twitter API, check it out!'), 'POST');
// get replies for the user
$info = $to->OAuthRequest('https://twitter.com/statuses/replies.xml', array(), 'POST');
Taking it further
There’s a few rocks left unturned here, such as dealing with the user denying the application’s approval request, storing in a database (although that’s pretty self explanatory) or updating the profile.
You can find a host of help at Twitter’s OAuth Wiki, or if you’re in need of some help from me, leave a comment below and I’ll try and get back to you as soon as I can!
The files can be downloaded by clicking here.
Thanks for reading, don't forget to subscribe to my full feed RSS if you want to stay updated!
If you liked this post, you may also like;
Readers thoughts
Social comments and analytics for this post…
This post was mentioned on Twitter by iDemonix: Check out my longest blog post yet; The Basics of the Twitter API – http://tr.im/GBME...
Thanks a lot, I am planning on doing just this kind of thing for a final year project in uni, so I will have to have an in depth look!
[Reply]
Hey Andy, that’s awesome, what kind of project you working on? I’m pretty experienced with the API now so if you ever need a hand drop me an email =]
[Reply]
Been wondering how all this works. OAuth always kinda.. scared me lol. I’ve had an idea for a twitter app for a while now.. see how it goes XD
[Reply]
hello world
[Reply]
Nice post. People only need ideas…With this code
[Reply]
Hi! very amused by the website .
[Reply]
Excellent tutorial!
At last, I understand how it all works.
Thank you very, very much.
[Reply]
Twitter itself has created a nice option where you can search the Twitter database on a specific keyword. The theory here is that if someone is tweeting related to a specific word they are likely interested in that topic.
[Reply]
Awesome tut, explains everything I needed to start authenticating with twitter accounts, and I’m sure I’ll be able to use that OAuth class to Authentify with other services.
[Reply]
I tried this and i got :
Fatal error: Call to undefined method OAuthUtil::parse_parameters() in /home/a4641298/public_html/inc/twitterOAuth.php on line 85
im kinda new at this so any help would be appreciated
thanks!
[Reply]
ok..looks like the zip file thats hosted has some issues… i went to the git site and got the two auth files. but now i have this issue from twitter when it jumps me to the allow/deny page:
Woah there!
This page is no longer valid. It looks like someone already used the token information you provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.
[Reply]
That’s too cool! I’m racking my brain for usage of this feature. I’m a DJ in San Diego, and thinking maybe I can mirror another site’s info into Twitter.
[Reply]
Can u plz explain How I can display user’s profile info through Saved token and token secret of database which save 1st time visit of page/link.
[Reply]
[...] Basics of using Twitter’s API from Dan Walker [...]
I tried to download your source code but the send.php and twitter.php contain no code at all, please reupload again, thanks.
[Reply]
Leave your comment