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
