OSAPI on iGoogle

Thursday, May 13, 2010 at 6:40 PM

The OpenSocial 0.9 specification introduced a simpler API called OS Lite (also known as OSAPI) which uses a syntax that's friendlier for Javascript developers.

Some steely eyed developers have already noticed that iGoogle works with most OpenSocial 0.9 features. The implementation of OSAPI should work as documented at opensocial.org.

Here's a basic example to play with so you can get started with the OS Lite API. In this example we will execute a request to fetch and display a list of the user's friends.


<Module>
 <ModulePrefs height="800" title="osapi friends" title_url="http://code.google.com">
  <Require feature="opensocial-0.9" />
  <Require feature="osapi" />
 <Content type="html" view="home">
  <![CDATA[
  <script>
   var result = '';
    osapi.people.get({userId:'@owner', groupId:'@friends'}).execute(function(response) {
    result += 'You have ' + response.list.length + ' friends:<ul>';
    for (item in response.list) {
     result += '<li>' + response.list[item]';
    }
    document.getElementById("output").innerHTML = result + '</ul>';
   });
  ]]>
 </Content>
</Module>



To keep it short we've omitted detailed error handling in our example. It should be pretty clear what the script is doing but it's good to check response.error and gracefully handle problems.
The first call, osapi.people.get({userId: '@owner', groupId: '@friends'}) constructs a request object to get a list of people for the current user from their friends group. The call to execute will make a call to the service, passing the results to a callback function. Our callback is a simple anonymous function that across the result set.
When running the code, look at the JSON response from iGoogle and you'll see that the data structure is pretty straightforward. Use some of the tools built into your browser such as:
  • Firebug if you are using Firefox
  • Chrome or Safari Developer tools.
  • Opera Dragonfly
  • Internet Explorer 8's debugger

These tools help debug your Javascript but also can show you the HTTP messages that are going to iGoogle from your gadget and the responses iGoogle sends back. There's also the OpenSocial Developer App which is a gadget that will build arbitrary messages that you can incorporate in test code.

As we get more OpenSocial 0.9 tested out on iGoogle, we'll update the documentation to reflect the current functionality.

If you like OSAPI and you're going to be at Google I/O 2010, you can find us in the Hack Alcove on May 20 2010 from 2-3:30pm. We'll give a walk through of a gadget built with osapi for iGoogle gadget developers. There's also a talk for iGoogle developers at I/O on May 20 2010 at 10:15am.