LearnOpenSocial Tutorial

writes on September 21, 2009

Want to reach more than 500 million users with your social app? OpenSocial is the key. The OpenSocial standard will allow you to build apps that work across a number of massive social networks, including MySpace, Orkut, Ning, hi5 and LinkedIn (complete list).

OpenSocial defines an API for developing social apps and was designed in cooperation with multiple social networks right from the start. Amongst many others, companies like Google, Yahoo!, LinkedIn and MySpace support the interface.

Editor’s Note: Looks like The Future of Web Apps will definitely sell out. Speakers: Twitter, Facebook, Google, Six Apart, digg / Kevin Rose, Mozilla, Dustin Diaz and more.

OpenSocial Tutorial

I’m going to walk you through building a simple chat application using the OpenSocial API. You can download the complete code for the application here.

If you want to follow our example in code, a few smaller preparations are necessary. These are necessary mainly because of the fact that OpenSocial development only really makes sense inside of a real social platform which provides the API. Isolated on your home desktop it makes little sense because the basic platform is only available online, from the inside (embedded into) the platform.

For our example, you need a free Orkut account (a valid Google account is also sufficient) and access to the Orkut developer sandbox. The setup of your Orkut account including access to the developer sandbox is described in the document OpenSocial-Tutorial for Orkut in the segment “Running your first Gadget”.

Because chatting without friends isn’t very exciting, it’s vital that you also add a few friends to your Orkut account. If you can’t get any of your colleagues to also register for the Orkut sandbox, you can simply create a second Google/Orkut account, open that one in another browser, add yourself (the other Orkut account) as a friend and then install the app as well.

If you want to program your own Gadget and also make changes to the example code provided, you need a little webspace, including PHP and a MySQL. The other preparations for this are documented in the Readme file in the download archive.

Google Gadgets as a Foundation

The basis for an OpenSocial application is a so-called Google Gadget, which could be familiar already to some developers from experiences with iGoogle, e.g.

A Gadget is an XML document and is merely the frame for an OpenSocial app.
An exemplary Gadget definition could look as follows:

<?xml version="1.0" encoding="UTF-8" ?>
  <ModulePrefs title="Chat Tutorial">
      <Require feature="opensocial-0.8" />
  <Content type="html">
         // here comes our application code...

The real application code is defined within the <Content> node of the Gadget and consist of HTML and JavaScript (while the embedding of Flash or Silverlight objects is possible too). All following JavaScript code snippets in this article belong inside of this <Content> node.

Initialize the App

Because we work with JavaScript within our Gadgets, at first we should wait until the page has completely loaded to be able to initialize our application cleanly. From Javascript frameworks like jQuery or Prototype you’re probably already used to getting informed as soon as the DOM is ready and we can begin with the initialization. Google’s Gadget-API also has such a helper function:


Querying for Data in OpenSocial

An important part of our chat application is a simple list of our friends. To find out who our friends are (and how many we have) we ask our social network container (which is Orkut in our example). The corresponding JavaScript function “load_friends”, which we called on initialization, looks like this:

function load_friends(){
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
    var friends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
    req.add(req.newFetchPeopleRequest(friends, {}), 'viewer_friends');

From this example we see how data queries work in OpenSocial:

In the first line we create a “DataRequest” object. All requests which we would like to have answered are appended to this object subsequently; in our example we first add a query for the profile data of the “Viewer” and then a query for his friends by calling req.add().

Because we work exclusively with JavaScript and HTML here, data queries are also carried out asynchronously through JavaScript (using AJAX).

It’s only in the last line of our example that the request is really sent through req.send(). It’s worth noting that, with this concept of querying, we can immediately take care of several data queries in only one request – instead of needing several AJAX requests and generating traffic and latency several times. Google calls this procedure “batch requesting”.

At the same time, looking at that code snippet, you can clearly see what it’s all about in OpenSocial: it’s about “people data” and the relations of the people to each other. Two types of persons are the most interesting, which is why the API defines them as constants:

One of them is the “VIEWER”. The Viewer is the (logged in) user who’s looking at the profile page on which our application is installed. The other one is the “OWNER”, which is the owner of the profile page on which the Gadget is installed. It is perfectly possible that the Owner and the Viewer at times are the same user – when the owner is looking at his own profile page, using the application.

In addition to Viewer and Owner, it is also possible to request data about other users by their user ID.

As we sent off our requests we had given an additional parameter to the method req.send(). This was the reference to the function “on_load_friends” which is used as a callback and is automatically called as soon as our request was answered and returned data. Therefore, we can access the results of our query – the person data we asked for – inside of the function “on_load_friends”:

function on_load_friends(data) {
    var viewer = data.get('viewer').getData();
    var friends = data.get('viewer_friends').getData();

Accessing our data through the method “get()” is necessary because of the “batch requesting”. While putting together the query, we had provided the strings ‘viewer’ respectively ‘viewer_friends’ as a last parameter. This was necessary because we wanted to request multiple data packages in one go – and of course we want to be able to distinguish them again at the end. Through data.get (‘viewer’).getData () we get the return values which we had named ‘viewer’ when we put together the request.

Now in the next step we want to show our friends in a list:

friends.each(function(friend) {
    friends_html += '<div class="friend_name"> '+ friend.getDisplayName()+ '</div>';

Those of you who have already worked with Ruby or the JavaScript framework Prototype will probably know the “each” notation. The OpenSocial-API provides this function, too. We use it here to iterate through the records of our friends.

By calling “getDisplayName()” on each of our friends records we use a special function of OpenSocial.

Most data fields are specific for a certain platform. This means e.g. that a field called “hobbies” that exists on MySpace might not exist in another container like Orkut at all. To at least be able to show a display name – in any case, and on any platform – a sensible return value from getDisplayName is guaranteed by the API.

In other cases we should be more careful by explicitly checking if a certain field that we’re trying to access really exists:

opensocial.getEnvironment().supportsField(opensocial.Environment.ObjectType.PERSON, opensocial.Person.Field.ID);

With this line of code, we can check if there’s a field called ‘id’ for objects of type ‘person’. As soon as we know that our field of choice really exists, we can access it through “getField()”:


A few specialities still have to be considered when sending a chat message:

function send_message(message, user_to, user_from){
    var post_data = { action: 'save_message', message: message, to_user: user_to, from_user: user_from};
    post_data = gadgets.io.encodeValues(post_data);
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA] = post_data;
    gadgets.io.makeRequest('http://www.example.com/message.php', function(){}, params);

Our self-defined method “send_message()” is used to send an entered message via AJAX to a remote server. This remote server then saves the message in a database until it is picked up by it’s receiver.

Inside of this function, the Gadgets-API is used heavily. This is necessary because it’s not easily possible for security reasons to send a request to an other than the origin server with AJAX. Here the Gadgets-API steps in, which makes this possible through “gadgets.io.makeRequest”.

Other Possibilities

The OpenSocial-API offers some more possibilities. With the help of the Activities-API you can, for example, read or write activity messages for a user. Therefore, an application would be able to read or write activity messages like “Mike has a new profile photo” or “Martin and Linda are friends, now”.

A so-called “Lifecycle event” can help developers gear into important points in the life cycle of an application. As a developer, you can for example, be informed when the deinstallation of a Gadget happens and take actions accordingly (by deleting old database entries, for example).

Another area of the API deals with data persistence. This functionality is exciting because OpenSocial apps – being “just a frontend” at first hand – come without their own backends and therefore have no database by default. Every social network can decide for itself to which extent it allows applications to persist data for a viewer.

The concept of “Views” is also an interesting part of OpenSocial development: An OpenSocial-Gadget can have different views. This depends on where the Gadget was integrated, respectively in which view a user is at this specificmoment. The current view can be requested at runtime so that, e.g., different functionalities can be offered depending on the currently active view of the Gadget.

Basically four different view types are defined in OpenSocial: The “Profile” view is active when it is viewed on the profile page of the user. The “Home” view is active when a Gadget is viewed on the personal homepage of the user (on which the above mentioned viewer and owner constants are always identical, because only the account owner has access to his personal homepage). The “Canvas” view is a view in which the Gadget is more or less alone on the page and therefore has a lot of space available. Finally, the “Preview” view has limited accesses and is intended for demo purposes.

Publishing your SocialApp

The development of an OpenSocial application always begins in a sandboxed developer environment where you can work on your application without interruptions. During this time, however, the app is only accessible to the developer himself (or other developers) – but not publicly to normal users.

Then – after some time of development and testing – when your SocialApp has a sufficient level of maturity and is ready to enrich the world, you can submit it to the respective social network to be checked and (hopefully) approved.

Though the submission process is a little different in every social network (as an example you find Orkut’s application form here), it always serves the same purpose: to put your submitted app through their paces.

If then, after several days or weeks, your application was found to be nice enough, it is included into the platform’s list of applications – and can be installed by all users of the platform.


Google’s OpenSocial-API only really offers the functionality that Facebook developers are already accustomed to. However, with OpenSocial, you can reach a wider and larger audience of 500 million people.

In day-to-day development, in spite of the wholehearted promise “Many sites, one API”, caution is advised: some of the networks don’t implement the complete specification or take awhile to implement updates to their APIs. Sometimes some minor differences in the API implementation force you to adapt to special situations (hi5, for example, requires the Gadget scaffolding to be a little bit more detailed).

The result so far that OpenSocial can present, however, looks good: excellent documentation, more than 30 involved social networks all over the world, and more than half a billion users.

0 Responses to “OpenSocial Tutorial”

  1. how can i add a friend part on my site (im using jaspers77 login system) and i want ppl to b able to add friends and see a list of awaiting friends to be accepted in a list upon them logging in how can i do this plz visit site and let me know feel free 2 sign up

  2. Can you help me to list the friends in a tabular format. Instead of listing friends in div or list . I want to put all friends in

  3. Do let me know if you want me to trim it down. ,

  4. Do let me know if you want me to trim it down. ,

  5. nice one Tobias Günther but i need more so just posting ….. thanks a lot

  6. Social networking such as Twitter is developing at dramatic speed these days. New functions keep being introduced into the market place. They are growing to be the most effective way to conduct marketing research as well as advertising.

  7. Integrated Data Storage
    A full-service data storage solutions provider, Integrated Data Storage, LLC provides customers with best of breed solutions for their data storage needs. In an era of “integrators” designing by discussion, outsourcing installations, and selling every product in the market, Integrated Data Storage, LLC believes in a short list of the best products implemented by a team with rigorous quality control processes and supported continuously as the environment around the solution evolves.

  8. very nice tutorial! im trying it out as we speak!

  9. Very good.
    Hi Tobias, I have one site about opensocial too (bu in portuguese).

Leave a Reply

You must be logged in to post a comment.

Learn to code with Treehouse

Start your 7 day free trial today and get access to hundreds of video courses in web development, design and business!

Learn more