Skip to content

Instantly share code, notes, and snippets.

@quandyfactory
Last active September 24, 2015 16:08
Show Gist options
  • Select an option

  • Save quandyfactory/773917 to your computer and use it in GitHub Desktop.

Select an option

Save quandyfactory/773917 to your computer and use it in GitHub Desktop.
shorturl.py
import httplib2
try:
import json
except:
import simplejson as json
def short_url(long_url='http://raisethehammer.org')
"""
Takes a long URL and returns a short URL.
Uses the Google URL Shortener API: http://code.google.com/apis/urlshortener/
"""
h = httplib2.Http('/path/to/.cache')
url = 'https://www.googleapis.com/urlshortener/v1/url?key=<api-key>'
req_headers = {"content-type": "application/json" }
data = { "longUrl": long_url }
response, content = h.request(url, 'POST', json.dumps(data), headers=req_headers)
if response.status != 200:
raise Exception('HTTP Error', response.status)
jsonobj = json.loads(content)
return jsonobj['id']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment