January 30, 2011

Using goo.gl with jsonlib

An example using jsonlib to invoke an inconvenient HTTP API from Javascript.

When Google released the goo.gl URL shortener API recently, they did not provide a JSONP API, so it is not convenient to make goo.gl URLs directly from Javascript. But then I wanted to implement a goo.gl-based "Save As Short Url" feature in the save box of Heidi's Sudoku Chrome App. The app is 100% Javascript and isn't even hosted on its own web server. What to do?

It is easy to do cross-domain HTTP by bouncing JSONP requests off call.jsonlib.com. With jsonlib, invoking the goo.gl API is just a few lines of code.

How To Do It

Here is how the goo.gl API works:

  1. You assemble a JSON string containing your long URL in the 'longUrl' field.
  2. This string must be POSTed to the googleapis server, with Content-Type "application/json".
  3. The response is JSON that will have your short URL in the 'id' field.

In Javascript, it is inconvenient to POST data that is not formatted as "application/x-www-form-urlencoded", and it is hard to use cross-domain HTTP requests that do not return script-formatted JSONP services. However, call.jsonlib.com solves both of these problems easily.

Here is the code for a goo.gl shortener wrapper that shows how it can be done with a single call to jsonlib.fetch:

<script src="http://call.jsonlib.com/jsonlib.js"></script>
<script>
function googlurl(url, cb) {
  jsonlib.fetch({
    url: 'https://www.googleapis.com/urlshortener/v1/url',
    header: 'Content-Type: application/json',
    data: JSON.stringify({longUrl: url})
  }, function (m) {
    var result = null;
    try {
      result = JSON.parse(m.content).id;
      if (typeof result != 'string') result = null;
    } catch (e) {
      result = null;
    }
    cb(result);
  });
}
// Make a short URL for a nicely written book.
googlurl('http://www.amazon.com/Numerical-Linear-Algebra-Lloyd-'
       + 'Trefethen/dp/0898713617', function(s) { alert(s); });
</script>

Voila! Short URLs in a single function call.

Play with the code here if you like.

Posted by David at January 30, 2011 11:53 AM
Comments

First, thanks for sharing David. I have been testing your solution for a while.

But, what I've found is that for some reason Goo.gl is creating 3 different shortened URLs with this method. Do you have any idea why this is happening, and can you think of a method to prevent this?

You will only notice this of course if you connect the Goo.gl shortening to your Google Account.

You find my solution where I'm testing this here:
http://www.savio.no/blogg/a/82/google-analytics-campaign-url-builder-with-short-url-and-twitter-posting

The only difference between your code and mine is that I have added a Google API Key and OAuthToken to the url like this:

url: 'https://www.googleapis.com/urlshortener/v1/url?key=myGoogleAPIKey&oauth_token=tokenGenerated'

Posted by: Eivind Savio at April 24, 2011 08:49 AM
Post a comment









Remember personal info?