October 8, 2010

Python - Shorten a URL Using Google's Shortening Service (goo.gl)

Using Python to shorten a URL with Google's shortening service (goo.gl):

 
#!/usr/bin/python 
#  Corey Goldberg - 2010

import json
import urllib
import urllib2


def shorten(url):
    gurl = 'http://goo.gl/api/url?url=%s' % urllib.quote(url)
    req = urllib2.Request(gurl, data='')
    req.add_header('User-Agent', 'toolbar')
    results = json.load(urllib2.urlopen(req))
    return results['short_url']


if __name__ == '__main__':
    print shorten('http://www.goldb.org/')
    print shorten('www.yahoo.com')

You give it a URL to shorten: shorten('http://www.goldb.org/long_url')

... and it returns a shortened URL for you: 'http://goo.gl/jh4W'

3 comments:

Cale Davis said...

This is a very handy command line tool. I hate opening up another browser tab to shorten URLs.

Omer said...

I a getting

urllib2.HTTPError: HTTP Error 401: Unauthorized

did google change something on their side?

rsdtom said...

Url shortening with httlplib2 and API_KEY support

https://gist.github.com/sauravtom/5161801