HTTP is an API

Ray Camden posted an interesting article over on InsideRIA about expanding short urls using jQuery and ColdFusion.  After reading the article, I thought he was overcomplicating things somewhat by relying on the url shortening services' APIs to do the lookups.  Yes, that's what APIs are for, but for this case, HTTP happens to be a perfectly sufficient API, it's consistent across services, it requires no special interface code, and it's crazy simple.  I commented to that effect, and then decided I ought to put my  money where my mouth is.

To that end, I wrote a small demo app that uses several different bits of tech to get the job done (render an ugly page with auto-expanding URLs).  It uses JSON/P to load some tweets containing shortened URLs from the Twitter Search API, writes them to the DOM with jQuery after wrapping the URLs with A tags (the part Ray did manually), and then wires a jQuery mouseover listener to trigger expansion (virtually identical to Ray's).  Of course, the server side is what I was actually interested in, so here it is:

<cfhttp method="get"
  url="#attributes.expand#"
  redirect="false"
  result="cfhttp" />
<cfoutput>#cfhttp.responseHeader["Location"]#</cfoutput>

Pretty simple, eh?  Both a rapier and a howitzer can kill a man; picking the right one is important.

Why does this work?  Because every service is just doing a HTTP 301 with a Location header from the short URL to the full URL.  Some of them expose APIs for creating and querying the short URLs, but for this task, we don't actually care, we only care about the Location header.  The only special processing require is for preview.tinyurl.com links; I simply convert them to normal tinyurl.com links so they do the "right" thing.

As always, there is full source (all 55 lines of it, in one CFM template) displayed beneath the app itself should you wish to see all the details.  The JavaScript stuff is far more complex than needed for a demo app, but I wanted to do a little experimentation on the client side as well as the server-side stuff.

3 responses to “HTTP is an API”

  1. BradB

    Good one.

  2. Sebastiaan

    And the mouseout function would be?