Skip to content

Instantly share code, notes, and snippets.

@ikks
Created May 31, 2012 19:43
Show Gist options
  • Save ikks/2845750 to your computer and use it in GitHub Desktop.
Save ikks/2845750 to your computer and use it in GitHub Desktop.
Using goo.gl from python 2.X Where X is 6 or more
#Given to the public domain
#No warranties
import urllib2
import simplejson
def shorturl(urltoshorten):
"""Compress the URL using goo.gl take a look at https://developers.google.com/url-shortener/v1/getting_started
>>> shorturl('http://igor.tamarapatino.org')
'http://goo.gl/FxHOn'
"""
try:
apiurl = "https://www.googleapis.com/urlshortener/v1/url"
req = urllib2.Request(apiurl,
headers={'Content-Type': 'application/json'},
data='{{"longUrl": "{0}"}}'.format(urltoshorten))
shorturl = simplejson.loads(urllib2.urlopen(req).read())['id']
except:
shorturl = urltoshorten
return shorturl
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment