Monday, May 4, 2009

URL shortening with Python and bit.ly

URL shortening has became the de-facto way of sharing links while micro blogging (Tweeting!).

Today, I was looking for a tool,  which will assist me shortening a group of URLs without the need to repress the annoying bookmarklet again and again.

I didn't find anything worth mentioning, so I've decided to hack my own tool.

I am using Python for most of my programming tasks, cause it is clean and simple !

The following Python code automates the process of shortening a long url using bit.ly wonderful service.

In order to use it, you'll need to pass the long URL, your bit.ly login and your bit.ly API key.

Your comments are welcome.

Download the code from pastebin

#!/usr/bin/python
import urllib

def shorten_url(long_url, login_user, api_key):
    try:
        longUrl = urllib.urlencode(dict(longUrl=long_url))
        login = urllib.urlencode(dict(login=login_user))
        apiKey = urllib.urlencode(dict(apiKey=api_key))
       
        encodedurl="http://api.bit.ly/shorten?version=2.0.1&%s&%s&%s" % (longUrl, login, apiKey)

        request = urllib.urlopen(encodedurl)
        responde = request.read()
        request.close()
        responde_dict = eval(responde)
        short_url = responde_dict["results"][long_url]["shortUrl"]
        return short_url

    except IOError, e:
            raise "urllib error "


if __name__ == '__main__':
    shorten_url('http://http://tux-log.blogspot.com', 'your_login', 'your_api_key' )

5 comments:

  1. thanks for your tips. I'v submitted a link of this article to our website in order to share it with more ppl. check:
    http://www.webmasterclip.com/story/url-shortening-python-and-bitly

    ReplyDelete
  2. I generally use http://aafter.us/ , but interested in your process. I need some more clarification. Is it only possible with bit.ly?

    Regards,
    SharonHill

    ReplyDelete
  3. You need a URL shortening service which has an API for developers. You can use tinyurl, cli.gs or bil.ly.

    ReplyDelete
  4. A great wrapper for the bit.ly API in python:
    http://code.google.com/p/python-bitly/

    ReplyDelete
  5. THANK YOU SO FREAKING MUCH! :)

    ReplyDelete