Over a million developers have joined DZone.
Platinum Partner

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

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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

#  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'

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Corey Goldberg , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}