TinyURL API in Python and C#

Sunday, May 24, 2009 03:00 PM

Did you know that tinyurl.com has an API? A few months ago while writing lensherr, I was poking around and discovered their API. All you have to do is make a HTTP GET request to this endpoint http://tinyurl.com/api-create.php with a url parameter of the url you want to tinyurl. It's that simple. Below are code snippets of working classes that I have used in past projects.

TinyURL Python class, that is included in my google code lensherr project.

class tinyurl:

        API_CREATE_URI = "http://tinyurl.com/api-create.php?url=%s"

        def __init__(self, url):
                self.url = url

        def create(self):
                encoded_url = urllib.urlencode({'url':self.url})[4:]
                new_url = tinyurl.API_CREATE_URI % (encoded_url)
                tinyurl_request = urllib2.Request(new_url)
                tinyurl_handle = urllib2.urlopen(tinyurl_request)
                return tinyurl_handle.read()

TinyURL C# class, that is included in my github repository here.

public static class TinyUrl
{
    public static string Create(string url)
    {
        string tinyUrlApiFormat = "http://tinyurl.com/api-create.php?url={0}";
        string tinyUrlCall = string.Format(tinyUrlApiFormat, HttpUtility.UrlEncode(url));
        string response = string.Empty;
        HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(tinyUrlCall);
        hr.Method = "GET";
        HttpWebResponse hwr = (HttpWebResponse)hr.GetResponse();
        using(System.IO.Stream receiveStream = hwr.GetResponseStream())
        using (System.IO.StreamReader sr = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
        {
            response = sr.ReadToEnd();
        }
        return response;
    }
}

Happy Hacking.