Corey Goldberg is a software developer from Boston. His interests include Python, Linux, Open Source, and Testing. Corey is a DZone MVB and is not an employee of DZone and has posted 31 posts at DZone. You can read more from them at their website. View Full User Profile

Using Python to Shorten a URL Using Google's Shortening Service (

  • submit to reddit

Using Python to shorten a URL with Google's shortening service (

#  Corey Goldberg - 2010

import json
import urllib
import urllib2

def shorten(url):
    gurl = '' % 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('')
    print shorten('')

You give it a URL to shorten: shorten('')

... and it returns a shortened URL for you: ''

Published at DZone with permission of Corey Goldberg, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)