Author Archive

Creating your first Twitter application with OAuth

Twitter has a ton of data. Whether or not it’s useful is another question, but we will never find out until we analyze that data.


The first step in exploring the Twitter API is registering your application with Twitter. Point your browser to http://twitter.com/apps and get started.

Set up the general information about your app, and upload a picture if you want. This icon will show up on the Twitter connections page once a user validates their account with your application.

Next, choose whether or not your app will run in a desktop app or the browser.

One of the more confusing settings is the “Callback URL”. This is the location that Twitter will redirect your users once they have authenticated their credentials at Twitter.com. I chose the home directory of http://twiggler.org because my main app has an index.php file with a switch statement checking to see whether or not the user is authenticated.

switch ($state) {
  default: /* create authentication link to twitter.com */
  case 'returned':
    /* If the access tokens are already set skip to the API calls */
    break;
}

Once you’ve given Twitter all of the information needed to create your application, hit Save.

Now Twitter spits back a key and a secret (if you are curious about what this means, check out my question on Stack Overflow). These are needed so that Twitter can identify you as the developer of your application. You use the access keys when making API calls to Twitter.

So now what?

That was really easy, right? But now how do you get at the data? What is the next step?

It’s time to learn about OAuth.

Instead of making a user type in their username and password when trying to use your application, you can just have them authenticate via Twitter. Sometimes users don’t always trust a third-party website with this level of personal information, so OAuth makes it easy for the user to give you access to their credentials without giving you the same password they may use as their bank account.

OAuth is kinda complicated, but some developers have made very easy-to-use librarys that you can just plug in to your site.

Let’s walk through how to use Twitter and OAuth to make API calls.

For this example, let’s use PHP and Abraham Williams’ Twitter OAuth Library.

The easiest way to get his example code is to clone this git repository. Here are some helpful tutorials on how to use github.

Once you’ve made a copy of his repository, take a look in the example folder. Open index.php and look at the opening lines of code:

// require twitterOAuth lib
require_once('twitteroauth/twitterOAuth.php');
 
/* Sessions are used to keep track of tokens while user authenticates with twitter */
session_start();
/* Consumer key from twitter */
$consumer_key = 'xWFhuNNKxiHYCcvFBgzA';
/* Consumer Secret from twitter */
$consumer_secret = 'ldO1ImQKdU4KQ98N8RR7Ts71JquYiwaPUk6836LUuw';
/* Set up placeholder */
$content = NULL;
/* Set state if previous session */
$state = $_SESSION['oauth_state'];
/* Checks if oauth_token is set from returning from twitter */
$session_token = $_SESSION['oauth_request_token'];
/* Checks if oauth_token is set from returning from twitter */
$oauth_token = $_REQUEST['oauth_token'];

I simply added the key and secret and saved the file. If you scroll a tad further, you will see the switch statement I mentioned earlier. It basically checks to see if you have been authenticated. If you haven’t, it displays the authenticate URL like this:

Here is the code used to build that button, found in the default section of the switch:

    /* Create TwitterOAuth object with app key/secret */
    $to = new TwitterOAuth($consumer_key, $consumer_secret);
    /* Request tokens from twitter */
    $tok = $to->getRequestToken();
 
    /* Save tokens for later */
    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
    $_SESSION['oauth_state'] = "start";
 
    /* Build the authorization URL */
    $request_link = $to->getAuthorizeURL($token);
 
    /* Build link that gets user to twitter to authorize the app */
    $content = 'Click on the link to go to twitter to authorize your account.';
    $content .= '</p><a href="'.$request_link.'"><img src="img/connect.gif" /></a><p>';

Now send the user to Twitter to either allow or deny you access to their data:

When the user clicks “Allow”, they are sent to your Callback URL (which is the same URL they just came from), but this time, the case ‘returned’ is switched on.

    /* If the access tokens are already set skip to the API call */
    if ($_SESSION['oauth_access_token'] === NULL && $_SESSION['oauth_access_token_secret'] === NULL) {
      /* Create TwitterOAuth object with app key/secret and token key/secret from default phase */
      $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
      /* Request access tokens from twitter */
      $tok = $to->getAccessToken();
 
      /* Save the access tokens. Normally these would be saved in a database for future use. */
      $_SESSION['oauth_access_token'] = $tok['oauth_token'];
      $_SESSION['oauth_access_token_secret'] = $tok['oauth_token_secret'];
    }
 
    /* Create TwitterOAuth with app key/secret and user access key/secret */
    $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
    /* Run request on twitter API as user. */
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');

Now you can display the contents of $content, and you should be able to see all of your data from Twitter’s verify_credentials API call.

Yes, it might seem like just random data, but you will learn how to work with this data in further chapters.

Please send me feedback for this, or if you have any questions, let me know.

For more detailed instructions, check out Abraham’s docs.

Comments (1)

Twitter Cross-Site Scripting Vulnerabilities

When a company releases an API to developers, there is always a possibility that a bad guy will get a hold of some code and put a lot of people in a bad mood.

Dave Naylor first posted about this, and I thought it would be something worth mentioning.

Leave a Comment

I updated the WordPress settings so that…

I updated the WordPress settings so that anyone can register, and their default role is a contributor. That means they can write posts, but they are only published if approved by an admin.

Comments (1)

The past, present, and future of the Twi…

The past, present, and future of the Twitter API. http://apiwiki.twitter.com/API-Overview

Leave a Comment

Using cURL to dig into the Twitter API

Twitter has some really good docs online for beginners to start using the Twitter API. If you have access to a command line, you can get started right away with a versatile tool called cURL.

curl http://twitter.com/statuses/public_timeline.rss

This is a simple command to get the latest tweets from the public timeline. It will return an RSS feed that is probably of little of no use to you right now. Let’s try something more useful.

curl -u username:password http://twitter.com/statuses/friends_timeline.xml

Make sure you use your username and password for this command. This will return the latest Twitter updates from the people you follow. Take a look at the data:

<status>
  <created_at>Mon Aug 31 00:32:37 +0000 2009</created_at>
  <id>3655460288</id>
  <text>Show a Bank of America card and get into a museum for free. Time to visit deYoung. (http://tr.im/xvJa)</text>
  <source>&lt;a href=&quot;http://www.nambu.com&quot; rel=&quot;nofollow&quot;&gt;Nambu&lt;/a&gt;</source>
  <truncated>false</truncated>
  <in_reply_to_status_id></in_reply_to_status_id>
  <in_reply_to_user_id></in_reply_to_user_id>
  <favorited>false</favorited>
  <in_reply_to_screen_name></in_reply_to_screen_name>
  <user>
	<id>940631</id>
	<name>Andrei Zmievski</name>
	<screen_name>a</screen_name>
	<location>San Francisco, CA</location>
	<description>I'm Russian. 'nuff said.</description>
	<profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/56772017/n3502094_30200385_24_normal.jpg</profile_image_url>
	<url>http://andreiz.tumblr.com</url>
	<protected>false</protected>
	<followers_count>1958</followers_count>
	<profile_background_color>170F00</profile_background_color>
	<profile_text_color>170F00</profile_text_color>
	<profile_link_color>A04521</profile_link_color>
	<profile_sidebar_fill_color>E6AA51</profile_sidebar_fill_color>
	<profile_sidebar_border_color>E6AA51</profile_sidebar_border_color>
	<friends_count>257</friends_count>
	<created_at>Sun Mar 11 18:05:57 +0000 2007</created_at>
	<favourites_count>143</favourites_count>
	<utc_offset>-28800</utc_offset>
	<time_zone>Pacific Time (US &amp; Canada)</time_zone>
	<profile_background_image_url>http://s3.amazonaws.com/twitter_production/profile_background_images/2909595/AZ-twitter.gif</profile_background_image_url>
	<profile_background_tile>false</profile_background_tile>
	<statuses_count>5015</statuses_count>
	<notifications>false</notifications>
	<verified>false</verified>
	<following>false</following>
  </user>
</status>

If you are new to XML, it’s a breeze. Think of it as “data about data”. It’s structured data. The Twitter API allows you to use XML and JSON (which I prefer personally because it’s easier to use with Javascript).

The last thing I will show you in regards to cURL is how to post an update.

curl -u username:password -d status="your message here" http://twitter.com/statuses/update.json

Make sure to escape any double quotes in your tweet.

You can do a ton of things with cURL, which I will explore in a later post. Play around with it, and let me know what you think. Here is another good resource about using cURL and Twitter.

Leave a Comment