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("<strong>fsockopen() error:</strong>$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"; <!-- Replace the following code for later examples from the article --> httpRequest('twitter.com'); echo "Response: <pre>$response</pre>\n";
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: <pre>$response</pre>\n";
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.

hans
September 26, 2007 at 1:30 pm
hans
September 26, 2007 at 12:30 pm
Dan Ozuna
sjvv.org
August 14, 2007 at 7:42 pm
Dan Ozuna
sjvv.org
August 14, 2007 at 6:42 pm
Dan Ozuna
sjvv.org
August 14, 2007 at 7:16 pm
Dan Ozuna
sjvv.org
August 14, 2007 at 6:16 pm
stef
August 11, 2007 at 12:57 am
stef
August 10, 2007 at 11:57 pm
Dan Ozuna
sjvv.org
August 7, 2007 at 10:25 pm
Dan Ozuna
sjvv.org
August 7, 2007 at 9:25 pm