Main Menu



You are here: Home
Using Google's Url Shortener API From Python PDF Print E-mail
Written by Josh B   
Thursday, 13 January 2011 15:23

Tags: google | python

Google has had an Url Shortener for a while now. Since the summer in fact. Google have now announced an API to use this service programatically via your favourite language. The advantage of using Google's Url Shortener is that (hopefully) it will be around for a while. It also allows one to view statistics from the urls generated without having to leave Google's arms, and the analytics shown are seriously impressive for a free service...!

Here is one way to use that service from Python.

Note that I've used the Client Login method to access the service. This allows us to store the generated urls, and view them if we log in at http://goo.gl/ . There is also the OAuth method. Why didn't I implement this...? Well, mostly since I am well acquainted already with Google's Client Login method through work...

To use the following code you will need your Google Account details to hand, have a Google API key registered, and some urls to mess about with.

#!/usr/bin/env python

import urllib2
import urllib
import json
import re
from StringIO import StringIO

def getTokenFromGoogle (username, password):
    url = "https://www.google.com/accounts/ClientLogin"
    params = {
            "accountType" : 'GOOGLE',
            "Email" : username,
            'Passwd' : password,
            'service' : 'urlshortener',
            'source' : 'ExcessiveDevelopment-UrlShortner-vs1'
            } 
    data = urllib.urlencode(params)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    dataFromGoogle = response.read()

    authTokenRe = re.compile(r"Auth=(.+?)$")
    match = authTokenRe.search (dataFromGoogle)

    if(match):
        return match.group (1)
        
    raise Exception, "could not authToken for user : %s" % username

def shorternUrlWithAuthToken (authToken, urlShortern):
    values = json.dumps({'longUrl' : urlShortern})
    requestUrl = "https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY
    googleAuthTokenHeader = "GoogleLogin auth=" + authToken
    print googleAuthTokenHeader
    headers = {
                'Content-Type' : 'application/json',
                'Authorization' : googleAuthTokenHeader
                }
    req = urllib2.Request (requestUrl, values, headers)
    response = urllib2.urlopen (req)
    the_page = response.read()
    io = StringIO(the_page)
    jsonReturned = json.load(io)
    return jsonReturned ["id"]

GOOGLE_API_KEY = "GOOGLEAPIKEY"
USERNAME = "my gmail address"
PASSWORD = "IZZASECRET"

authToken = getTokenFromGoogle (USERNAME, PASSWORD)

print "authToken : %s" % (authToken)

url = "http://www.slashdot.org"

shortUrl = shorternUrlWithAuthToken (authToken, url)
print "shortUrl : %s" % shortUrl 
Last Updated on Thursday, 13 January 2011 15:37
 

Add comment


Security code
Refresh

Joomla! Template by Red Evolution - Joomla Web Design