Created
March 14, 2013 14:31
-
-
Save sauravtom/5161801 to your computer and use it in GitHub Desktop.
Goo.gl url shortening wrapper for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from sys import argv | |
import httplib2 | |
import simplejson as json | |
#API_KEY = ADD YOUR API KEY HERE , even if you don't shurl will still work | |
def shurl(longUrl): | |
try: API_KEY | |
except NameError: | |
apiUrl = 'https://www.googleapis.com/urlshortener/v1/url' | |
else: | |
apiUrl = 'https://www.googleapis.com/urlshortener/v1/url?key=%s' % API_KEY | |
headers = {"Content-type": "application/json"} | |
data = {"longUrl": longUrl} | |
h = httplib2.Http('.cache') | |
try: | |
headers, response = h.request(apiUrl, "POST", json.dumps(data), headers) | |
short_url = json.loads(response)['id'] | |
except Exception, e: | |
print "unexpected error %s" % e | |
return short_url | |
if __name__ == '__main__': | |
print shurl(argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment