Web APIs by Example, Part I: Twitter

APIs, or application programming interfaces, are essentially standardized methods for applications to talk to one another and share information. In desktop applications, the operating system provides a full range of APIs in order for your programs to run and interact with it (in Windows an app might register itself as an option for when you right click an icon; or on a Mac an app will hide itself from the dock.) On the web, APIs are usually provided as a means of importing data to other services, or using third party clients to push information to your account.

Since Twitter is all the rage these days, I thought it would be a great starting point to introduce you to the world of web APIs and how simple they really are to work with. Twitter, like most presencing services, has a very limited range of API calls because, well, it’s a very simple service. The documentation for Twitter’s API can be found hrere. The Twitter API, all be it simple, has allowed great applications like Twitterific and Twittervision to be created.

Taking a REST

Web APIs come in a whole range of flavors; some require you to pass chunks of XML data back and forth, but most (including Twitter) use a simple method that’s known as the RESTful approach. REST stands for Representational State Transfer; it’s a fancy term for a pretty simple and straightforward process: using URLs as “interfaces” for reading and writing information to a service. This wikipedia article offers some good examples, but you should get the hang of things as we work along through this article and the follow ups.

PHP

These example articles will use PHP, for a couple reasons: it’s widely supported, most folks who are interested in web APIs use or know it already, and it’s a simple enough language that even if you’re not familiar with it you’ll be able to get a grasp of the ideas from it’s syntax. Porting the concepts here to any language of your choice should be simple enough. I’ll be using PHP4 to create these examples as it’s the most widely supported flavor, but they should be compatible with PHP5 without any modifications. Start by creating a “twitter.php” file; this is where we’ll be entering our code and working through the process of creating a simple Twitter app.

The Basics of Communication

Web applications that use REST speak over standard HTTP calls; the same form of communication that your web browser uses to request pages from a web server. When you requested this page, your browser pieced together a set of HTTP headers (a bunch of lines of data the provides information about what you want to access, what kind of browser you’re using, what kind of data you’re browser will accept, and other fun bits), opened a connected to my web server and then sent those headers. The web server responded by sending it’s own HTTP headers (likewise containing information about the server, what kind of data it will be sending you, and so on) followed by the data you’ve requested, in this case HTML. Although it may sound a little complicated if you’re new to it, it’s really not. You’ll see why.

Opening a Socket in PHP

Let’s begin by creating a PHP script to open a socket (a “tunnel” in which your app will send and receive data to a web server) to Twitter.

$twitter_username = 'YOUR_USERNAME_HERE';
$twitter_password = 'YOUR_PASSWORD_HERE';

$errno = 0;
$errstr = '';
$response = '';

function httpRequest($host, $path = '/', $method = 'GET') {

	global $errno, $errstr, $response;
	global $twitter_username, $twitter_password;

	$header  = "$method $path HTTP/1.1\r\n";
	$header .= "Host: $host\r\n";
	$header .= "Accept-Encoding: none\r\n";
	$header .= "Authorization: Basic " .
		base64_encode("{$twitter_username}:{$twitter_password}") . "\r\n";
	$header .= "Connection: Close\r\n\r\n";

	$sock = fsockopen($host, 80, $errno, $errstr, 30);
	if (!$sock) {
	    die("fsockopen() error:$errstr ($errno)");
	} else {
	    fwrite($sock, $header);
	    while (!feof($sock)) {
			$response .= fgets($sock, 128);
	    }
	    fclose($sock);

	    $response = trim(str_replace(array('<', '>'),
	    	array('<', '>'), $response));
	    return true;
	}

}

echo "

Contacting Twitter...

\n";


httpRequest('twitter.com');

echo "Response:
$response

\n";

Download Source Code

Here we’ve got some variables for storing response information (socket error number, socket error string and socket response data), a simple function that pieces together our HTTP headers, opens a socket and retrieves the response data from the server, and some simple interface code for exposing that response data. Right now we’re not talking to the API; we’re just making a simple HTTP call to Twitter’s servers, just like your browser would.

Note: Be sure to enter your Twitter details into $twitter_username and $twitter_password; the API calls we’ll be making next will require it.

Posting to Twitter

Now that we’ve got our app and Twitter on speaking terms, let’s move on to actually making an API call by posting a message to our Twitter account. The Twitter API is pretty straightforward; if you take a look at the documentation you’ll see there is an update method. This is what we’ll use. The API specifies that the URL syntax is: http://twitter.com/statuses/update.format?status=message. The message is, obviously, what you’d like posted to Twitter, while the format can either be xml or json – this is the format of the response that Twitter’s web server will respond to us in. In this example we won’t be interpreting this response, we’ll be using our own eyes to look at it. Let’s go with XML.

Replacing the two lines indicated in the previous example, let’s add our API call.

httpRequest('twitter.com', '/statuses/update.xml?status=Test+Test+1+2+3!', 'POST');

echo "Response:
$response

\n";

Download Source Code

If all went as planned, you should see a long bit of response beginning with a ‘HTTP/1.1 200 OK’. If you got a message indicating it couldn’t authenticate, you didn’t set the $twitter_username and $twitter_password variables in the previous code. Check your Twitter account, and you should see your new message. Congratulations, you’ve just written to the Twitter API!

That’s the Basics

So those are the fundamentals of writing to a web API. If you’ve never done it before, you’re probably surprised how simple it is. Next time, I’ll use a slightly more complicated API and demonstrate how to read and interpret calls from it. Stay tuned.

Tags: , , ,

View Comments

  1. Hi. I am a blind webmaster for a non-profit Veterans organization. I’ve been asked to install WordPress and set things up so that the “most recent” posts appear on our home page. Is using PHP and API calls something I can use to get this done? I’m a total newbie when it comes to this and I would appreciate any help/advice on this.

  2. Hi. I am a blind webmaster for a non-profit Veterans organization. I’ve been asked to install WordPress and set things up so that the “most recent” posts appear on our home page. Is using PHP and API calls something I can use to get this done? I’m a total newbie when it comes to this and I would appreciate any help/advice on this.

  3. Hi Dan,

    As far as I know WordPress doesn’t have any API for that sort of thing, though it does have an API (called MetaWeblog) that lets you use clients to create and edit posts. Assuming your WordPress installation is going to be on the same site as the homepage you want to display your “Most Recent” posts on, you can just write a PHP script to query your WordPress database, pull the latest posts, and output it on your page.

    If you’re not familiar with PHP, you might try Googling around; I imagine this sort of thing is pretty popular. It’s a simple enough script to write though, so don’t be afraid to dig into the PHP documentation and try it.

    Good luck, and let me know if you have any more questions.

  4. Hi Dan,As far as I know WordPress doesn’t have any API for that sort of thing, though it does have an API (called MetaWeblog) that lets you use clients to create and edit posts. Assuming your WordPress installation is going to be on the same site as the homepage you want to display your “Most Recent” posts on, you can just write a PHP script to query your WordPress database, pull the latest posts, and output it on your page.If you’re not familiar with PHP, you might try Googling around; I imagine this sort of thing is pretty popular. It’s a simple enough script to write though, so don’t be afraid to dig into the PHP documentation and try it.Good luck, and let me know if you have any more questions.

  5. Hey Evan, nicely written post thanks for the insight on twitter api. Lead me into looking up a couple of other site api’s ( delicio.us, google, amazon, paypal ). There are a LOT of sites nowadays offering different methods to interchange with their services, and it is very interesting to see the methods the big guys use to allow access to their data.

    Short note for Dan, WordPress is nice, for blogging but if your site is community oriented, I will throw in a quick word for Drupal. It has integrated blogs , customisable themes, tons of modules, and after the small initial learning curve ( 1 month, about ), you will find yourself ‘hooked’.

    Retrieving queries of last posts (from multiple blogs) , with Drupal is very easy. for an example see my **unfinished ** homepage, http://www.3wsimple.com/ , sorry it s not really up to date I am badly overloaded. But it should give you a good idea. Hop on to drupal.org, if
    you want more info, or contact me through above site if you need a helping hand. End of shameless plug, thanks for the nice read evan !, keep up the nice work !

  6. Hey Evan, nicely written post thanks for the insight on twitter api. Lead me into looking up a couple of other site api’s ( delicio.us, google, amazon, paypal ). There are a LOT of sites nowadays offering different methods to interchange with their services, and it is very interesting to see the methods the big guys use to allow access to their data.Short note for Dan, WordPress is nice, for blogging but if your site is community oriented, I will throw in a quick word for Drupal. It has integrated blogs , customisable themes, tons of modules, and after the small initial learning curve ( 1 month, about ), you will find yourself ‘hooked’.Retrieving queries of last posts (from multiple blogs) , with Drupal is very easy. for an example see my **unfinished ** homepage, http://www.3wsimple.com/ , sorry it s not really up to date I am badly overloaded. But it should give you a good idea. Hop on to drupal.org, ifyou want more info, or contact me through above site if you need a helping hand. End of shameless plug, thanks for the nice read evan !, keep up the nice work !

  7. Thanks very much for the tips, stef, and the kind words. Good luck with your site!

  8. Thanks very much for the tips, stef, and the kind words. Good luck with your site!

  9. Hi Evan,

    I did a few Google searches and came across this bit of PHP. I’ve been going through the PHP documentation and a nice tutorial I found. But in the mean time could you look at this code for me? Are there any Changes/enhancements I should make?

           
            # ” rel=”bookmark” title=”Permanent Link: “> in  

  10. Hi Evan,I did a few Google searches and came across this bit of PHP. I’ve been going through the PHP documentation and a nice tutorial I found. But in the mean time could you look at this code for me? Are there any Changes/enhancements I should make?               # ” rel=”bookmark” title=”Permanent Link: “> in  

  11. Hi Stef,

    Thanks for the tip about Drupal. A few people I know have said that they use it and love it. They also say it is very screen reader friendly which is a big plus. I’ve taken a quick look at it, but haven’t had the time to really dive in. May I ask what language your site is in? It’s always… interesting to hear when my screen reader switches to a different language and starts butchering it. At least I think it is butchering it. Just curious. Thanks again.

  12. Hi Stef,Thanks for the tip about Drupal. A few people I know have said that they use it and love it. They also say it is very screen reader friendly which is a big plus. I’ve taken a quick look at it, but haven’t had the time to really dive in. May I ask what language your site is in? It’s always… interesting to hear when my screen reader switches to a different language and starts butchering it. At least I think it is butchering it. Just curious. Thanks again.

  13. thanks for the reply on the e-mail I will try to post another comment to try to repeat the error :)

  14. thanks for the reply on the e-mail I will try to post another comment to try to repeat the error :)

  15. hai Evan i tried your code,but iam getting maximum execution time of 60 secs exceeded at $response .= fgets($sock, 128); ,will u pls suggest me a solutionfor this

Leave a comment

blog comments powered by Disqus