symbol blog  ·  archive  ·  about  ·  Feed feed

TinyURL API in Python and C#

Sunday, May 24, 2009 03:00 PM

Did you know that 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 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 = ""

        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)

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

public static class TinyUrl
    public static string Create(string url)
        string tinyUrlApiFormat = "{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.