Shortening Urls using bit.ly

September 18, 2010

At some point, twitter stopped automatically shortening my urls, which caused lots of "Status is over 140 characters" errors. I decided to fix this on my side by automatically shortening urls using bit.ly.

Signup at http://bit.ly

The first stage is to signup to bit.ly. Once you have done this, login and go to http://bit.ly/a/your_api_key/. This will give you the login credentials you need from your code. I added these two values as properties in my settings.py file as BIT_LY_LOGIN and BIT_LY_API_KEY.

Python Code

Here's a function that uses the v3 bit.ly api, takes a long url as a parameter and returns the shortened one. There are three return formats available, json, xml and txt. We'll use the txt version here for simplicity, as we're running python 2.5 in production which doesn't have json support.

def _shorten_url(pUrl):
    """
    Shorten url using bit.ly api
    """
    lRequest = "/v3/shorten?format=txt&longUrl="
    lRequest += pUrl
    lRequest += "&login=" + settings.BIT_LY_LOGIN + "&apiKey=" + settings.BIT_LY_API_KEY
    lConnection = httplib.HTTPConnection("api.bit.ly")
    lConnection.request("GET", lRequest)
    lResponseObject = lConnection.getresponse()
    lStatusCode = lResponseObject.status
    lShortUrl = lResponseObject.read()

    if lStatusCode == 200:
        return lShortUrl
    else:
        return pUrl

References