Google recently added an API to their goo.gl URL shortening service.
Currently, you can shorten, elongate and list your URLs. There are several ways to authenticate using the API, but I went with OAuth since it allows you to keep a list of unique shortened URLs. I decided to write a little library for use with Alternity, but first there are a few steps.
1. Make sure that the URL shortening service is active in your Google API Console
2. Register your domain with Google here
Registering your domain and putting in Target URL path prefix will enable your OAuth consumer key and OAuth consumer secret.
The next few steps will be familiar to anyone who has dealt with OAuth before, but Google has a few twists.
I used ruby’s oauth gem for this, currently version 0.4.4, so if you’re missing it just sudo gem install oauth.
Your first step is to create a consumer with your key and secret:
consumer = OAuth::Consumer.new(ConsumerKey, ConsumerSecret,
{:site => "https://www.google.com",
:request_token_path => "/accounts/OAuthGetRequestToken",
:access_token_path => "/accounts/OAuthGetAccessToken",
:authorize_path=> "/accounts/OAuthAuthorizeToken",
:signature_method => "HMAC-SHA1"})
Now you need to get your request tokens. Google adds a scope parameter. This can be a comma separated list of Google services, but I only care about the url shortener.
request_token = consumer.get_request_token({:oauth_callback => "http://www.SOMEURL.com"},
{:scope => "https://www.googleapis.com/auth/urlshortener"})
Grab the authorization url
request_token.authorize_url
and paste that into your browser. You’ll be taken to Google where you will be given the choice to either allow or deny access to the service. When you select allow, Google will redirect back to your oauth_callback url and add some parameters:
http://www.SOMEURL.com/?oauth_verifier=big_long_string&oauth_token=big_long_string
You’ll want to note the verifier and the token. They’re url encoded so I decoded them. Just ran them through php’s url_decode on the command line.
php -r “echo url_decode(big_long_string);”
Now you need your access tokens
access_token = request_token.get_access_token(:oauth_verifier =>OAUTHVERIFIER FROM URL ABOVE)
Pull out your access token and access secret with access_token.token and access_token.secret and save them somewhere.
Now when you need to use the api in your web app, it’s a two step process.
1. Get the consumer using the same process as above.
2. Create the access token
access_token = OAuth::AccessToken.new(consumer, ACCESSTOKEN, ACCESSSECRET)
Get your history
response = access_token.get('https://www.googleapis.com/urlshortener/v1/url/history')
history = JSON::parse(response.body)
Shorten a url
h = Hash.new
h["longUrl"] = "http://www.something.com"
j = h.to_json
response = access_token.post('https://www.googleapis.com/urlshortener/v1/url', j, { 'Content-Type' => 'application/json' })
shortURL = JSON::parse(response.body)["id"]