Skip to content

Instantly share code, notes, and snippets.

@myano
Forked from ikks/goo.gl.py
Created November 13, 2013 21:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myano/7456396 to your computer and use it in GitHub Desktop.
Save myano/7456396 to your computer and use it in GitHub Desktop.
#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