Orkut Application Platform

Requesting orkut Albums and Photos

Jason Cooper, orkut Team
Februrary 2009

The Albums API is a recent addition to the OpenSocial specification, enabling application developers to request and display the current user's albums and photos. This article guides you through the functions available for fetching this data from orkut and how to use it in your applications.

Before your application can retrieve a user's albums and photos, that user must first check the box labeled "Allow access to my photos" on the install page:

Once a user checks this box and installs the application, that app can then fetch the user's albums via the methods and endpoints detailed below. Note that applications can only retrieve the albums and photos owned by the current user (i.e. VIEWER)—this means that album requests targeting other users or groups won't return any data. Further, orkut only returns albums shared with "everyone in orkut"—albums with more restrictive privacy settings, including those shared only with friends, are not accessible through the API.

API Overview

Fetching albums and photos using the JavaScript API follows the same conventions as fetching other data such as profile details for individuals and groups using the standard OpenSocial API. orkut's Albums API merely adds several new request methods for retrieving collections of albums and media items, so if you have experience with requesting data in OpenSocial, the new API should seem very familiar. If you don't, please read the Requesting Data in OpenSocial article before going forward.

If users haven't granted your application permission to access their albums by enabling the checkbox on the application will return a null in response to any of the requests described below. Likewise, if the current user doesn't have the application installed, orkut will return a null object, just as it does for other data requests, with a 401 (Unauthorized) status code.

Fetching a collection of albums

Fetching a collection of albums is syntactically similar to fetching people in orkut. A new opensocial.DataRequest method, newFetchAlbumsRequest, has been made available for this purpose. This method accepts an opensocial.IdSpec object as its first parameter (see this overview of OpenSocial identifiers for details on IdSpec objects), which indicates which user or group of users to fetch albums for. You may also pass in an optional second object specifying additional request parameters. Here are the possible values:

Parameter Name Accepted Values Description
ALBUM_ID JavaScript array of album IDs Specifies which albums to fetch; passing an empty list results in a fetch of all albums.
FIRST JavaScript number Specifies the starting index to use for paging purposes; objects are returned beginning from this index.
MAX JavaScript number Specifies the number of objects to return (defaults to 20); for performance reasons, it is often preferable to fetch a limited number of objects in a single request and MAX is used to specify the limit.

A typical request for the current user's albums should look similar to the following snippet:

var req = opensocial.newDataRequest();
var idspec = opensocial.newIdSpec({'userId':'VIEWER', 'groupId':'SELF'});

req.add(req.newFetchAlbumsRequest(idspec), 'viewerAlbums');
req.send(fetchAlbumsHandler);

Notice that aside from the new method call, the request looks very similar to this request for retrieving a list of friends. The opensocial.DataRequest object is created in the same way and the send method is used just as it is for standard requests with a callback function being passed as an argument. This function will be executed when the albums are returned just as with the other OpenSocial asynchronous methods. As with people requests, album requests return an opensocial.Collection object. You can access each opensocial.Album instance contained within by iterating through the collection using its each method, just like the example in the earlier article.

Here is a sample callback function for the previous request which iterates through the returned opensocial.Album objects. See below for a more compelling sample.

function fetchAlbumsHandler(resp) {
  var viewerAlbumsResp = resp.get('viewerAlbums'); // use the key passed with the request to "get" the appropriate data

  if (!viewerAlbumsResp.hadError()) {
    var viewerAlbums = viewerAlbumsResp.getData();

    viewerAlbums.each( // the 'each' method is used to iterate through every object in collection
      function(album) {
        // do something with each album
      }
    );
  }
};

Fetching a collection of photos

Naturally, photo albums store photos, so the Albums API introduces a new request for fetching the photos from a given album— newFetchMediaItemsRequest, added to the opensocial.DataRequest class, returns an opensocial.Collection object containing a set of opensocial.MediaItem instances representing the photos in the album. The newFetchMediaItemsRequest method accepts three parameters: an opensocial.IdSpec object representing the owner of the album and the ID of the album containing the photos to retrieve.

These opensocial.MediaItem objects have additional methods and properties not in the opensocial.MediaItem class defined in v0.8 of the API—this new interface follows the specification defined for OpenSocial v0.9.

Below is a request for the photos in one of the albums fetched above:

var album = viewerAlbums.asArray()[0];
...

if (album != null) {
  var req = opensocial.newDataRequest();
  var idspec = opensocial.newIdSpec({'userId':album.getField(opensocial.Album.Field.OWNER_ID), 'groupId':'SELF'});

  req.add(req.newFetchMediaItemsRequest(idspec, album.getId()), 'albumPhotos');
  req.send(fetchPhotosHandler);
}

The fetchPhotosHandler function is passed into send and automatically executed when the photos are available. Here is a simple implementation of this callback which iterates through the collection of opensocial.MediaItem instances. To see what you can do with these MediaItem objects, see the next section.

function fetchPhotosHandler(resp) {
  var albumPhotosResp = resp.get('albumPhotos'); // use the key passed with the request to "get" the appropriate data

  if (!albumPhotosResp.hadError()) {
    var albumPhotos = albumPhotosResp.getData();

    albumPhotos.each( // the 'each' method is used to iterate through every object in collection
      function(photo) {
        // do something with each photo
      }
    );
  }
};

Complete example

The following sample application demonstrates how you can build an application around the new functionality provided by the Albums API. This application first displays all user albums that are publicly viewable (i.e. shared with everyone). Then, when an album's thumbnail is clicked, the photos in that album are displayed in a grid underneath the table of albums.

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="List Albums example">
    <Require feature="opensocial-0.8"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
      <style type="text/css">
        img {
          border: solid gray 1px;
        }
        #photoGrid img {
          float: left;
          width: auto;
          margin-right: 10px;
        }
        table {
          border: solid gray 1px;
          background-color: #EEEEEE;
          margin-bottom: 15px;
        }
      </style>
      <script type="text/javascript">

        // Fetches all of the viewer's albums that are publicly viewable (i.e.
        // "shared with everyone"
        function fetchAlbums() {
          var req = opensocial.newDataRequest();
          var idspec = opensocial.newIdSpec({'userId':'VIEWER', 'groupId':'SELF'});

          req.add(req.newFetchAlbumsRequest(idspec), 'viewerAlbums');
          req.send(fetchAlbumsHandler);
        };

        // Callback function, executed when orkut finishes fetching the viewer's
        // public albums
        function fetchAlbumsHandler(resp) {
          var viewerAlbumsResp = resp.get('viewerAlbums');

          if (!viewerAlbumsResp.hadError()) {
            var viewerAlbums = viewerAlbumsResp.getData();

            // Add a table row for each album
            viewerAlbums.each(
              function(album) {
                createAlbumRow(album);
              }
            );
          }
        };

        // Adds a new table row for the passed album, displaying its thumbnail,
        // name, and description
        function createAlbumRow(album) {
          var row = document.createElement('tr');
          var thumbnailCell = document.createElement('td');
          var descriptionCell = document.createElement('td');

          // Add an image tag to the first cell with the album's thumbnail;
          // also include an event handler which executes fetchPhotos
          // when the image is clicked, passing in the album's ID.
          thumbnailCell.innerHTML =
            '<img src="' + album.getThumbnailUrl() +
            '" onclick="fetchPhotos(\'' + album.getId() + '\')"/>';

          // Output the album's title...
          descriptionCell.innerHTML =
            '<b>' + gadgets.util.escapeString(album.getTitle()) + '</b>';

          // ... and description
          descriptionCell.innerHTML +=
            '<p>' + gadgets.util.escapeString(album.getDescription()) + '</p>';

          row.appendChild(thumbnailCell);
          row.appendChild(descriptionCell);

          // Add the new row to the table
          document.getElementById('albumTable').appendChild(row);
        };


        // Fetches all photos from the album with the passed ID
        function fetchPhotos(albumId) {
          var req = opensocial.newDataRequest();
          var idspec = opensocial.newIdSpec({'userId':'VIEWER', 'groupId':'SELF'});

          req.add(req.newFetchMediaItemsRequest(idspec, albumId), 'albumPhotos');
          req.send(fetchPhotosHandler);
        };

        // Callback function, executed when orkut finishes fetching the
        // requested media items
        function fetchPhotosHandler(resp) {
          document.getElementById('photoGrid').innerHTML = '';
          var albumPhotosResp = resp.get('albumPhotos');

          if (!albumPhotosResp.hadError()) {
            var albumPhotos = albumPhotosResp.getData();

            // Add each photo's thumbnail to the photo grid
            albumPhotos.each(
              function(photo) {
                addToPhotoGrid(photo);
              }
            );
          }
        };

        // Adds the passed photo's thumbnail to the photo grid
        function addToPhotoGrid(photo) {
          document.getElementById('photoGrid').innerHTML +=
            '<img src="' + photo.getThumbnailUrl()+'"/>';
        };

        // Execute fetchAlbums function when gadget loads
        gadgets.util.registerOnLoadHandler(fetchAlbums);
      </script>

      <!-- Table to display album thumbnail and metadata -->
      <table id="albumTable" cellspacing="5"></table>

      <h2>Photos from selected album:</h2>

      <!-- Styled div to display photos from selected album -->
      <div id="photoGrid"></div>
    ]]>
  </Content>
</Module>

Notice that several album methods are called above, including getTitle, getDescription, and getThumbnailUrl. To get a full list of methods and properties, see the opensocial.Album reference.

Here is a screenshot of this application in action. You can see the albums listed in the table at the top with the photos displayed beneath it.

More resources

For more on requesting albums and other social data in orkut, please see the following links:

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.