The first step is exploring the methods we can call in the Google APIs Explorer. The method in the Blogger JSON API collection that most people use, understandably, is the method to list the most recent posts for a Blog –
posts.list. This method takes one required field – the
blogId that identifies a particular blog – and a number of optional arguments that allow us to tune what information is returned.
The information I am requesting from the Blogger JSON API is the post titles and content for the code.blogger.com blog which has a
blogId of 3213900. To limit the returned data to just the post titles and content, we use the optional argument
fields with the value of
items(content,title). Here is a link to the Google APIs Explorer with the appropriate information pre-filled so you can see both the underlying query that is sent to the Google APIs servers, as well as the shape of the returned JSON data.
To load the library, all we have to do is include a script in our HTML that loads the library as follows:
The part of this code to pay attention to is the argument
onload=init. This nominates the
init function is where we configure the client key and the API we want to work with:
function init() gapi.client.setApiKey('YOUR_API_KEY'); gapi.client.load('blogger', 'v2', function() // ... );
You can retrieve the API Key from your project on the Google APIs Console, once you have requested that I enable the Blogger API for your project. The
gapi.client.load function takes the API name, and version, of the API you want to use, and a callback function to run once the API support code has been loaded. In this code, we are loading the Blogger v2 API.
gapi.client.load callback, we have the following code to configure a request to the Google APIs servers:
var request = gapi.client.blogger.posts.list( 'blogId': 3213900, 'fields': 'items(content,title)' );
request.execute(function(response) // ... );
The execute method takes a callback function that will be executed once the Google APIs servers respond. The most important part of this callback function is the data that is handed to us in the
response argument. In the body of the callback function, I iterate over the items member to pull out the titles and contents of all the returned posts:
for (var i = 0; i < response.items.length; i++) $("#target").append("<h2>" + response.items[i].title + "</h2>"); $("#target").append(response.items[i].content); if (i+1<response.items.length) $("#target").append("<hr/>");
The eagle eyed among you will have noticed that I am using jQuery to insert the returned HTML into the DOM. I am using the latest stable jQuery hosted on Google’s Libraries API.
You can see the results on code-blogger.appspot.com. I have used HTML5 Boilerplate as the starting point for building this example, to get all the latest HTML5 magic. If you have any questions about this sample, please post them to the Blogger Developers Group. Read More