Social

How to Use the Twitter API


Can you type in your Twitter id, and copy/paste 4 things? If so, you too can use the Twitter API. It sounds daunting, like it’s some complex thing that would be nearly impossible to master — but in reality it’s extremely easy. Before we can start using it, however, you have to first sign up for it. To sign up for it, you must be using a phone-verified Twitter account.

phone verified account twitterOnce you have a phone verified account, visit https://dev.twitter.com/apps/new. We will fill this page out to get our API keys. For name, type in “My Super Cool Twitter Program” or something like that — anything will do. Description can be anything. Website can be anything (it doesn’t matter). Callback URL, just leave it blank. Click “Yes, I agree” on the developer agreement, and then click “Create your twitter application”.

twitter create an application

On the next page, you will see 4 tabs, “Details, Settings, Keys and Access Tokens, Permissions”, click on the Keys and Access Tokens. 2 of the 4 things you need are already done on that page, so copy and save the “Consumer Key (API Key)” and the “Consumer Secret (API Secret)”. You’re half way there! Scroll to the bottom of the page, and you will see a button called “Create my access token”, click it. Afterwards, under “Your Access Token”, you’ve got the final two things you need, the “Access Token” and the “Access Token Secret”.

twitter create access token

You should have your 4 thingamajiggies you need to access the Twitter API now. I’m pasting a copy of what they should look like (I jumbled my tokens around so they’re not real). Those are:

  • Consumer Key (API Key) uapiS0kDtQobOvbr32e5nmgMi
  • Consumer Secret (API Secret) 3A0DsDqmVquzu8CYBSiIOL4A4tXYHFbNRMaLvqQVXlDhGA8H7M
  • Access Token 3869525118-RL4uO8s8UdVAW9DBXKodB2GL4pquEsxREfqX0U6
  • Access Token Secret 24BwnkFj70tOpznq2WivfY1lu6fHwEEyL6c8C4RRr0Zp5

Now for our next step, you’re going to need a PHP server either installed on your home computer, or you need to rent a VPS (virtual private server) and install PHP on that, or even a cheapie shared hosting account that can run PHP will work — as long as that server has cURL access. cURL is simply a method that your PHP server can fetch external webpages. cURL will be fetching pages from Twitter, is the reason you need it working.

step 4 Wamp Server

Save the page below as “test.php” on your server. You’re going to make your first API call now! There are four things you absolutely need to change, which are the 4 API keys which you saved from the steps above. Paste them into the source code. Then load the page.

<pre><?php

// ***** SAMPLE USE OF TWITTER API *****
// ***** THIS PAGE WILL GRAB THE FIRST 10 FOLLOWERS OF BOB VILA *****

$twitteraccount = "bobvila";

// ***** NUMBER OF ACCOUNTS TO RETURN. MAX IS 200 AT A TIME *****

$thecount = "10";

$oauth_access_token = "3769525118-RL4uO8s8UdVAW9DBXKodB2HL4pquEsxREfqX0U6";
$oauth_access_token_secret = "24BwnkFj70tOpzng2WivfY1lu6fHwEEyL6c8C4RRr0Zp5";
$consumer_key = "uapi60kDtQobOvbr32e5nmgMi";
$consumer_secret = "3A0DsDqmKquzu8CYBSiIOL4A4tXYHFbNRMaLvqQVXlDhGA8H7M";

// ***** YOU SHOULDN'T HAVE TO CHANGE ANYTHING BELOW HERE

$maxid = '979999999999999999';

function buildBaseString($baseURI, $method, $params) {
	$r = array();
	ksort($params);
	foreach($params as $key=>$value){
		$r[] = "$key=" . rawurlencode($value);
	}
	return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
	$r = 'Authorization: OAuth ';
	$values = array();
	foreach($oauth as $key=>$value)
		$values[] = "$key=\"" . rawurlencode($value) . "\"";
	$r .= implode(', ', $values);
	return $r;
}

$url = "https://api.twitter.com/1.1/followers/list.json";

$oauth = array('screen_name' => "$twitteraccount",
			   'count' => $thecount,
			   'max_id' => $maxid,
			   'oauth_consumer_key' => $consumer_key,
			   'oauth_nonce' => time(),
			   'oauth_signature_method' => 'HMAC-SHA1',
			   'oauth_token' => $oauth_access_token,
			   'oauth_timestamp' => time(),
			   'oauth_version' => '1.0'
			 );					
						
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

// Make requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
				  CURLOPT_HEADER => false,
				  CURLOPT_URL => $url."?screen_name=$twitteraccount&count=".$thecount.'&max_id='.$maxid,
				  CURLOPT_RETURNTRANSFER => true,
				  CURLOPT_SSL_VERIFYPEER => false);

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json,true);

print_r($twitter_data);

?></pre>

After loading the page, you should see all kinds of follower data show. If you view source, the results should look a little something like this:

<pre>
Array
(
    [users] => Array
        (
            [0] => Array
                (
                    [id] => 266038428
                    [id_str] => 266038428
                    [name] => Jill Berry
                    [screen_name] => Realtorberry
                    [location] => Melbourne Florida
(etc)
</pre>

Congratulations! You just made your first API call. You just loaded the followers of a twitter account. Though the above example only attempts to load 10 accounts, this particular API call can load 200 at a time. You can make this API call 15 times in 15 minutes (or once per minute. That’s 200 accounts loaded per minute, 12,000 per hour, 288,000 per day. If you were only using one API account, you could load all the data on 4.35 million accounts once every 15 days. Use 4 accounts, with 4 APIs, and you can collect information on every follower in less than 4 days.

All we need to do is add some logic in order to cycle through all the followers of an account, then (once finished), cycle to the next account. Keep going until finished with all accounts, then start again at the beginning. On the second pass through, if someone suddenly became active again, we’ll update the database to reflect that the person is now active. The database will be 4.35 million rows, and all of our Twitter accounts will load people to follow from that huge pool of accounts.

I hope you can see just how easy this is, so far. It is not difficult to use the Twitter API. On the next page in this series on Twitter, we will create a database to hold information about these Twitter accounts. I will show you how to extract the important data from the Twitter API, and then we’ll database each user, how many followers they have, how many people they follow, and finally, when the last time was that they tweeted.

Social
Do Social Signals Help Rank Your Website?
Social
Using Blackhat with Twitter to get Whitehat Links for SEO
Social
How to Make Money with Twitter
There are currently no comments.

+ 34 = 37