Skip to content

Instantly share code, notes, and snippets.

@giginet
Created April 18, 2012 15:22
Show Gist options
  • Select an option

  • Save giginet/2414306 to your computer and use it in GitHub Desktop.

Select an option

Save giginet/2414306 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
#
# shorten.py
# created by giginet on 2012/04/18
#
from urllib import quote
from urllib2 import Request, HTTPError, urlopen
import json
API_URL = u'https://www.googleapis.com/urlshortener/v1/url'
def shorten(url):
try:
data = json.dumps({ 'longUrl' : quote(url) })
req = Request(API_URL, data)
req.add_header('Content-Type', 'application/json')
r = urlopen(req)
return json.loads(r.read())['id']
except HTTPError:
return url
if __name__ == '__main__':
print shorten(u'http://www.kawaz.org/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment