did you know tinyurl has an api?

tinyurl is a simple one-purpose service.  And it correspondingly has a delightfully simple “api”.  If you ever want to automatically create tinyurls from within an application, you can just request “http://tinyurl.com/api-create.php?url=$URL”, and you get back a text/plain document which contains the created tinyurl (and nothing else).  Couldn’t be easier to use.

It seems to work whether or not you url-encode your $URI, but it seems sketchy to me to NOT url-encode it, and better to do so, so I do.

Here’s an example in ruby of a method that will use this ‘api’ to give you a tinyurl for a url. I choose to catch any exception (tinyurl goes down? Takes away their api service?), by simply using the original url.

require 'open-uri'
require 'cgi'

def tinyurl(url)
  begin
    open("http://tinyurl.com/api-create.php?url=#{CGI.escape(url)}").read
  rescue
    # On an error, we just skip the tinyurl and use an ordinary one. 
    url
   end
 end
This entry was posted in General. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s