Wednesday, March 04, 2009

Consuming Blogger web-service using JSON

Blogger, which hosts my blog, started publishing its web-services using JSON in addition to the traditional XML type. I was intrigued by a Chris Coyier’s social home page and wanted to use it to learn about consuming JSON as well as create a similar “Social Home Page” for myself.

Chris Coyier’s sample site is an excellent starting point, as it uses 3 very basic web-services (Flickr, Twitter and ScrnShots) and in addition it uses JQuery to retrieve the JSON data and write it to the web-page. The first thing that I did to convert it into my own web-site was to retrieve my Flickr ID. The simplest way to do this is to use the idGettr page (I just could not find a page on Flickr from where I could retrieve my flickr id).

The Flickr web-service URL is: http://api.flickr.com/services/feeds/photos_public.gne?ids=YOUR_FLICKR_ID_HERE&lang=en-us&format=json&jsoncallback=? (The format query parameter tells Flickr to respond to your request using JSON).

The URL is provided as a parameter to JQuery’s $.getJSON method. In addition, you provide $.getJSON a method that is used to process the returned JSON.

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?ids=YOUR_FLICKR_ID&lang=en-us&format=json&jsoncallback=?", function(data){
      $.each(data.items, function(index, item){
        $("<img/>").attr("src", item.media.m).appendTo("#flickr")
              .wrap("<a href='" + item.link + "'></a>");});
    });

Using JQuery, makes it extremely easy to display the data on the web-page. In the above example, the JSON data is passed to the method, where the $.each iterator is used to iterate over each of the items in the JSON object. Another method, then processes the information in the item property and appends it to the div with class “flickr”. The code might seem very hard to understand at first, but if you download the example and step through it, it will make sense.

Next, I updated the twitter URL to point to my Twitter account. This too uses a scheme that is similar to how Flickr was consumed on this page.

Finally, I decided to get rid of the ScrnShots data on the page and instead use the new Blogger API that returns a JSON object. This took me a while as the API seems to be in beta and does not have a lot of documentation.

Here is how I did it.

For consuming the JSON version of the Blogger API, I decided to use a different approach (instead of using $.getJSON). This is the method that is documented on the Blogger blog and calls the web-service via the script element.

1. Create a method that will be used as the call-back method. I made my method extremely simple and all it does is, it captures the returned JSON object:

<script type="text/javascript" >
    var myBloggerJson = null;
    function handleJson(json) {myBloggerJson = json;}
</script>

2. Next call the web-service using the URL: http://YOUR_BLOGGER_BLOG_URL.blogspot.com/feeds/posts/default?alt=json-in-script&callback=handleJson. The important elements are the query parameter “alt” which is set to “jason-in-script”, which instructs blogger to return the data as a JSON object and the “callback” query-parameter, which holds the name of the method that will be called back with the JSON data.

<script type="text/javascript" src="http://BLOGGER_URL.blogspot.com/feeds/posts/default?alt=json-in-script&callback=handleJson"></script>

Important: the call-back method should be defined before the line where you include the script line which calls the blogger service. Otherwise, you will get an error.

In my example here, the handleJson method stores the returned JSON object in a variable called myBloggerJson.

3. Finally, I consume the Blogger JSON object using JQuery, using the following code:

$.each(myBloggerJson.feed.entry, function(index, entry){
           if (index < 8)
           {    $("#blogger").append('<div class="tweet"><p>' + "<a href='" + entry.link[4].href + "'>" +  entry.title.$t + "</a><br />" + '</p></div>');
           }
       }); 

If you look at the code, you will see that to be able to consume a JSON object, you need to know the structure of the JSON object. As this was my very first foray into using JSON and because the Blogger JSON structure is not documented, I had to figure the structure out manually. This was painfully slow as I was using the Visual Studio debugger and had to use the QuickWatch window to interrogate the object to determine its structure.

I later found out a much more easier way to determine the structure of the JSON object and this easier method uses a tool called a “JSON object inspector”. If you type in the URL to the web-service in your browser’s address bar, you will find that it returns a long string. If you copy this text and put it into the inspector you should be able to determine the structure of the JSON object. JSON Viewer, a CodePlex open source tool is one that is easy and robust to use. The following screen shot shows you the structure of the Blogger JSON structure.

image The important elements are: JSON-Object -feed --title ---$t : Blog title --entry ---entry[0]……..entry[n] : represent blog posts ------title : post title ------link : post links --------link[0]……link[4] : URLs to blog. [4] represents the friendly URL ------content : blog post content

If you now look at the code that consumes the Blogger JSON structure using JQuery, you will see that I post the latest 8 posts from my blog, using only the title, which is hyperlinked to the blog-post.

Check out the completed page at: http://www.aggregatedintelligence.com/Samples/MySocialPage/

2 comments:

Amber said...

Hi Raj

Thanks soo much for your tutorial & the jsonviewer link.


After 5 yrs of using blogger and learning the new curves as blogger continuously goes through a platform metamorphasis, I have noticed that the popular widgets that are created aren't using the right json calls, or that they aren't adjusting when blogger's code changes - the end result is allot of frustration with bad functions.


So I have decided to delve into json myself and rework some of these widgets.


Your post is very interesting and something I can start with.

Cheers!

Dean said...
This comment has been removed by a blog administrator.