Monday, January 2, 2012

Using Javascript to query the Google APIs

Tonight I decided to see how easy it would be to query Google+ programmatically using the Google APIs.  All up, it took me about 20 minutes from beginning to end to get the following screenshot running in a browser.


The first thing you need to do is to create an account and get yourself an API Key.  You do this through the API console.  This allows you to select which services you would like to work against and then assigns you a key that you use to access those services.  In my case, I just selected the Google+ service but there’s some really useful services that I need to look at in future such as Translate and Url Shortner.  Here’s an image of part of that screen:


Once I set up my access, I headed to the API Explorer to get a feel for the API that I would be querying.  The API Explorer is an awesome tool which lets you explore each of the APIs and run queries against them to get back results.  Here is a screenshot of the Google+ API running inside of the API Explorer:


Basically, you select the API, and then choose which method you want to execute, you fill in the parameters and then hit Execute to get back the results.  Running the activities.list method with my parameters returned some JSON in the results view so that I could see what data would be returned:


As you can see in the above image, the query returns an items collection with properties for each item returned.  For example, in the image above, you can see the title for the first G+ entry is “Nice, easy workflow”, and that the URL for that entry is displayed just below that.

Armed with my API Key and some knowledge about the API, next I created a web page and started coding.  The following Javascript executes a query against the activities.list method of the Google+ API for my userId.


As you can see, the steps are pretty straightforward.

  1. Load the Google API client script and supply a callback to handle the loaded event for the API
  2. In the callback, set your API key and load the API you want to use
  3. Configure a request and execute it

The final method to display is the method that I used to display the list of results on the page called enumerateResults in the image above. That method simply takes the list of results and appends them to a HTML list element using some of the properties that we saw in the API Explorer for that API’s results:


So that’s it.  20 minutes from beginning to end.  Some other useful links that you might find handy if you want to work against the Google API’s are:

No comments:

Post a Comment