Welcome Developers!

in

Welcome!

in

Using the Simplified JavaScript API

The OpenSocial 1.0 spec brought some interesting changes to the Myspace platform, but one often overlooked piece of the 1.0 pie is the new simplified JavaScript API.

One of the major complaints about the legacy JavaScript API found in OpenSocial version 0.8, which lives in the opensocial namespace, is that it is very verbose. Let’s take a look at an example; the snippet below shows how you would fetch a list of 100 friends in a 0.8 app:

function fetchFriends(){
var request = opensocial.newDataRequest();

var params = {};
params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1;

var idspec = opensocial.newIdSpec(params);

params = {};
params[opensocial.DataRequest.PeopleRequestFields.FIRST] = 1;
params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100;

request.add(request.newFetchPeopleRequest(idspec, params), FRIEND_KEY);
request.send(outputFriends);
}

The new API, which lives in the osapi namespace, is a little more succinct. Let’s take a look at a code snippet that has the exact same functionality only rewritten to use the osapi API:

function fetchFriends() {
osapi.people.getViewerFriends({
'count': '100',
'startIndex': '1'
}).execute(outputFriends);
}

You can plainly see the difference. The first example has 16 lines of code and uses 519 characters, the second example has 6 lines and 127 characters. As we all know, the less code the better: it’s easier to read and understand and less bugs will be introduced. The osapi API also has a very jQuery-like feel to it, which more and more developers are becoming used to.

When it comes to parsing the response the osapi API has further simplified things. Let’s say that after we execute the request above we want to access the first friend’s thumbnail URL. First let’s see how it’s done in the legacy API:

var pic = response.get("friends").getData().asArray()[0].getField(opensocial.Person.Field.THUMBNAIL_URL);

And now in the osapi API:

var pic = response.result.entry[0].thumbnailUrl;

A large difference to be sure.

Now that we’ve seen the benefits of the osapi API let’s talk about what it can and can’t do in relation to the legacy API. In terms of accessing and manipulating data (fetching friend lists, updating app data, creating albums, etc) the two APIs have the same functionality. Any data you can access or manipulate using the legacy API can be done with the osapi API.

Outside of data access you’ll still need to use the opensocial or gadgets namespace for most everything else. The osapi API just simplifies data access. So, for example, to share the app you’ll still need to do something like this:

function rsa(friend_array){
var body = "Hey [recipient]! [sender] wants you to ";
body += "add [app]. It's way awesome!";

var reason = opensocial.newMessage(body);

opensocial.requestShareApp(friend_array, reason, rsaCallback);
}

And to resize the height of the app when it loads, you’ll still need to do something like this:

function resize(){
gadgets.window.adjustHeight();
}
gadgets.util.registerOnLoadHandler(resize);

So how exactly does the new API work? The best place for technical documentation is the official spec. This first link introduces the osapi namespace and describes how to batch and send requests and handle errors:

http://opensocial-resources.googlecode.com/svn/spec/1.0/Core-Gadget.xml#osapi

This next link describes the different services that are defined in the spec and how to use them. Keep in mind that Myspace doesn’t support everything in the spec and we also define some services that aren’t in the spec — more on this later.

http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-Gadget.xml#JavaScriptAPIReference

Because the osapi API uses the same JSON input and output as the REST API, it can be useful to take a look at that spec as well:

http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-API-Server.xml#services

Finally, probably the quickest way to start using osapi is to use a sample app we have developed:

http://www.myspace.com/games/play/195871

The app lists all of the services that Myspace currently supports along with all the available parameters that can be specified. Simply click the service you want to use and fill in all the parameters you want. At this point you can click one of the three buttons:

  1. Execute. This will send the specified request to the server and output the result.
  2. Add to Batch. This will add the request to the batch, which is just a queue of requests. You can see the current state of the queue by clicking the *Batch* tab. From the *Batch* tab you can execute the batch or generate the sample code (see point 3 below).
  3. Generate Sample Code. This will display code that can be used in your app to execute the exact request you have specified.

Let’s look at an example. Say you want to find the viewer’s first five friends that don’t have the app installed. To make this happen just follow these steps:

  1. Click the People tab
  2. Under Method click getViewerFriends (you could also click get and specify @me under UserId and @friends under GroupId, but this is a handy shortcut)
  3. Enter 5 in the Count field
  4. Click hasApp under FilterBy
  5. Click equals under FilterOp
  6. Enter false in the FilterValue field
  7. Enter 1 in the StartIndex field
Figure 1: Request parameters
Figure 1: Request parameters

The desired parameters are now entered in (see Figure 1). At this point you can make sure the request will do what you think it will do by executing it and checking the results (see Figure 2).

Figure 2: The response
Figure 2: The response

Once you’re satisfied that you’re getting the correct data you can click Generate Sample Code to see what the code would look like.

Figure 3: Sample code
Figure 3: Sample code

The sample code can now be copied and pasted into your app.

Note: you can see that a function named myCallback is passed in as a parameter to the execute() function. You’ll need to define this myCallback function to correctly handle the callback from the request. If you don’t do this you’ll get an error. You may or may not want to rename myCallback to something more appropriate.

You can play around with all the functionality that the osapi API provides and take away some custom sample code that you can pop right into your app, hopefully you’ll find it useful.

Happy coding!
Chad Russell

For reference the complete code of the two sample apps that were used to test the code in the article are below.

1.0 app

 <Module xmlns:os="http://ns.opensocial.org/2008/markup" >
  <ModulePrefs title="MiscTest1.0" description="A test app">
    <Require feature="opensocial-1.0"/>
    <Require feature="opensocial-templates"/>
  </ModulePrefs>
  <Content type="html" view="canvas">

<button onclick="rsa(FRIEND_ARRAY)">share</button>
<div id="output"></div>
        
<script type="text/javascript">
//<![CDATA[

var FRIEND_KEY = "friends";
var FRIEND_ARRAY;

function fetchFriends() {
  osapi.people.getViewerFriends({
    'count': '20',
    'startIndex': '1'
  }).execute(outputFriends);
}

function outputFriends(response){
  var friends = response.result;

  if(!friends.error){
    var friend_array = friends.entry;
    FRIEND_ARRAY = [];

    for(var i = 0; i < friend_array.length; i++){
      writeToOutput(friend_array[ i ].displayName);
      FRIEND_ARRAY.push(friend_array[ i ].id);
    }
  }
  else{
    writeToOutput(friends.error.code + " -- " + friends.error.message);
  }

  gadgets.window.adjustHeight();
}

function rsa(friend_array){
  var body = "Hey [recipient]! [sender] wants you to ";
  body += "add [app]. It's way awesome!";

  var reason = opensocial.newMessage(body);

  opensocial.requestShareApp(friend_array, reason, rsaCallback);
}

function rsaCallback(response){
  // 0 is cancel
  // 1 is send
  // -1 is error
  var data = response.getData().result;
}

function resize(){
  gadgets.window.adjustHeight();
}

function writeToOutput(msg){
  document.getElementById("output").innerHTML += msg + "<br />";
}

gadgets.util.registerOnLoadHandler(fetchFriends);
gadgets.util.registerOnLoadHandler(resize);

// ]]>
</script>

  </Content>
</Module>

0.8 app

<button onclick="rsa(FRIEND_ARRAY)">share</button>
<div id="output"></div>

<script type="text/javascript">

var FRIEND_KEY = "friends";
var FRIEND_ARRAY;

function fetchFriends(){
  var request = opensocial.newDataRequest();

  var params = {};
  params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
  params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1;
           
  var idspec = opensocial.newIdSpec(params);

  params = {};
  params[opensocial.DataRequest.PeopleRequestFields.FIRST] = 1;
  params[opensocial.DataRequest.PeopleRequestFields.MAX] = 20;

  request.add(request.newFetchPeopleRequest(idspec, params), FRIEND_KEY);
  request.send(outputFriends);
}

function outputFriends(response){
  var friends = response.get(FRIEND_KEY);

  if(!response.hadError()){
    var friend_array = friends.getData().asArray();
    FRIEND_ARRAY = [];

    for(var i = 0; i < friend_array.length; i++){
      writeToOutput(friend_array[ i ].getDisplayName());
      FRIEND_ARRAY.push(friend_array[ i ].getId());
    }
  }
  else{
    writeToOutput(friends.getErrorCode() + " -- " + friends.getErrorMessage());
  }

  gadgets.window.adjustHeight();
}

function rsa(friend_array){
  var body = "Hey [recipient]! [sender] wants you to ";
  body += "add [app]. It's way awesome!";

  var reason = opensocial.newMessage(body);

  opensocial.requestShareApp(friend_array, reason, rsaCallback);
}

function rsaCallback(response){
  // 0 is cancel
  // 1 is send
  // -1 is error
  var data = response.getData();
}

function resize(){
  gadgets.window.adjustHeight();
}

function writeToOutput(msg){
  document.getElementById("output").innerHTML += msg + "<br />";
}

gadgets.util.registerOnLoadHandler(fetchFriends);
gadgets.util.registerOnLoadHandler(resize);
</script>

Comments

 

Twitter Trackbacks for Using the Simplified JavaScript API - MySpace Developer Team News and Announcements [myspace.com] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Using the Simplified JavaScript API - MySpace Developer Team News and Announcements         [myspace.com]        on Topsy.com

February 3, 2011 1:32 PM
 

Fred said:

This doesn't look complicated at all... I can do this... Thanks for the info by the way.

December 4, 2012 6:01 PM
 

w . gold said:

Great,Thanks for sharing.

December 4, 2012 10:20 PM
 

Helen said:

thank you worked great !

March 5, 2013 11:09 PM
 

Dan Gold said:

awesome article, thanks for this. it really helped me a lot!

March 10, 2013 11:03 PM