Developer's Guide: Java

Picasa Web Albums allows client applications to view albums and photos in the form of Google Data API feeds. Your client application can use the Picasa Web Albums Data API to upload photos and query for items that match particular criteria.

In addition to providing some background on the capabilities of the Picasa Web Albums Data API, this guide provides examples for interacting with the API using the Java Google Data APIs Client Library. For help setting up the client library, see the Getting Started Guide.

If you're interested in understanding more about the underlying protocol used by the Java client library to interact with the Picasa Web Albums API, see the protocol guide.

Audience

This document is intended for programmers who want to write client applications that can interact with Picasa Web Albums.

This document assumes that you understand the general ideas behind the Google Data APIs protocol. It also assumes that you know how to program in Java.

The code examples in this document use the Java client library; see the client library documentation for more information and more (non-Picasa Web Albums-specific) examples.

Getting Started

Picasa Web Albums uses Google Accounts for authentication, so if you have a Google account you are all set. Otherwise, you can create a new account.

For help setting up the client library, see the Getting Started Guide. To use the Java client library, you'll need the JDK 1.5+, and you should also be current on all patches.

To begin writing a Java application using the client library, you will need to add the following import statements to your Java source file:

import java.io.File;
import java.net.URL;

import com.google.gdata.client.*;
import com.google.gdata.client.photos.*;
import com.google.gdata.data.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.photos.*;

Authentication

The Java client library can be used to work with either public or private feeds. Public feeds are read-only, but do not require any authentication. Private feeds require that you authenticate to the Picasa Web Albums servers. This can be done via ClientLogin username/password authentication or AuthSub proxy authentication.

Single-user "installed" client authentication

To use ClientLogin (also called "Authentication for Installed Applications"), create a PicasawebService object, then invoke the setUserCredentials method to set the user ID and password,

PicasawebService myService = new PicasawebService("exampleCo-exampleApp-1");
myService.setUserCredentials("liz@gmail.com", "mypassword");

You can now use this object to make authenticated requests (like inserts).

For more information about the authentication systems of the Google Data APIs, see the Google Account Authentication documentation.

Multiple-user web application client authentication

The AuthSub login protocol allows your web-based application to have a user authenticate through Google's servers.

To authenticate a user using AuthSub, you have to follow these general steps:

  1. Construct the AuthSub URL.
  2. Send the user to a Google page to enter their AuthSub credentials.
  3. When the user returns, acquire a session token.
  4. Create a PicasawebService object.
  5. Tell the client library to use the given session token for interaction with the service, using the setAuthSubToken method.

Follow the instructions in the AuthSub and Google Data APIs client library documentation to acquire a session token, using the getRequestUrl, getTokenFromReply, exchangeForSessionToken, and setAuthSubToken methods. The scope string to use is:

https://picasaweb.google.com/data/

It'll look something like this:

String requestUrl =
    AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
                        "https://picasaweb.google.com/data/",
                        false,
                        true);
String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken, null);
PicasawebService.setAuthSubToken(sessionToken, null);

After you've called the PicasawebService object's setAuthSubToken method, the client library sends the token with every request, so you don't need to do anything further with the token.

Working with Albums

Albums are the way Picasa Web Albums groups photos into useful sets. These albums can be public or unlisted, and have their own properties such as a geographic location, a description, or a date.

You do not have to authenticate to retrieve data about public albums, but in order to create content, you must authenticate using one of the methods discussed in the authentication section.

Request a list of albums

To request the feed of albums belonging to user username, you can use the following Java code.

URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/username?kind=album");

UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);

for (AlbumEntry myAlbum : myUserFeed.getAlbumEntries()) {
    System.out.println(myAlbum.getTitle().getPlainText());
}

The getFeed method method handles all of the communication with Picasa Web Albums—it sends the HTTP GET request, it receives the redirect (if any), it sends the second GET request, it waits for the XML response to arrive, and it parses the XML and assigns the element contents and attribute values to appropriate parts of the given feed object.

If an error occurs during the getFeed call, the client library generates an appropriate exception, so your code should be prepared to handle exceptions.

The final line of the above code calls the feed's getTitle method, which returns a TextConstruct object. To transform the text construct into a String, we call the title's getPlainText method.

Working with Photos

When uploading photos, you have to authenticate a service object using one of the methods discussed in the Authentication section.

Request a list of photos

There are different ways to retrieve photos. The most common is to get a list of all of the photos in an album, but you can also retrieve recent photos from a user.

List photos in album

This is the basic query to retrieve all of the photos belonging to username in the albumid album. The title of each photo is then printed out to the console.

The string "default" can be used in place of a real username, in which case the server will use the username of the user credentials used to authenticate the request.

URL feedUrl = "https://picasaweb.google.com/data/feed/api/user/username/albumid/albumid";

AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);

for(PhotoEntry photo : feed.getPhotoEntries()) {
    System.out.println(photo.getTitle().getPlainText());
}

List photos recently uploaded

It is also possible to retrieve the photos associated with a user, but without specifying any particular album. The snippet below will retrieve the latest photos uploaded by username and print their titles.

URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/username?kind=photo");

AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);

for(PhotoEntry photo : feed.getPhotoEntries()) {
    System.out.println(photo.getTitle().getPlainText());
}

Accessing photo information

In previous examples, only the title of a photo was printed out. However, many different metadata fields can be retrieved about a photo— such as EXIF information, thumbnail URLs, the ID of the album it is a part of, and more.

System.out.println("Title: " + photo.getTitle().getPlainText());
System.out.println("Description: " + photo.getDescription().getPlainText());
System.out.println("ID: " + photo.getId());
System.out.println("Camera Model: " + photo.getExifTags().getCameraModel());
System.out.println("Geo Location: " + photo.getGeoLocation());
System.out.println("Media Thumbnail: " + photo.getMediaThumbnails().get(0).getUrl());

The above example prints out different pieces of information from a PhotoEntry. It also demonstrates how to retrieve elements from the gphotos namespace. The thumbnail and image URLs are taken from the MediaRSS elements inside of the entry. The camera data, if available, is found inside of the exif namespace.

Upload a new photo

Upload new photo with metadata

You can upload a photo to Picasa Web Albums using the insert method of the PicasawebService object. The following demonstrates uploading a new photo named "puppies.jpg," with the title "Puppies FTW," and the description "Puppies are the greatest." We assume that myService is an authenticated PicasawebService object. Note that "image/jpeg" is the valid MIME type of our "puppies.jpg" file, but adjust for whatever photo file you are uploading. See the protocol guide for the types of files that are supported, along with their MIME type.

URL albumPostUrl = new URL("https://picasaweb.google.com/data/feed/api/user/username/albumid/albumid");

PhotoEntry myPhoto = new PhotoEntry();
myPhoto.setTitle(new PlainTextConstruct("Puppies FTW"));
myPhoto.setDescription(new PlainTextConstruct("Puppies are the greatest."));
myPhoto.setClient("myClientName");

MediaFileSource myMedia = new MediaFileSource(new File("/home/liz/puppies.jpg"), "image/jpeg");
myPhoto.setMediaSource(myMedia);

PhotoEntry returnedPhoto = myService.insert(albumPostUrl, myPhoto);

The MediaFileSource object specifies a source file on the local disk for the photo; you can instead use MediaSource to use an image from another kind of data stream. The insert method pulls the image data from the specified file or stream and sends it to Picasa Web Albums.

The setClient method sets the name of the client that's uploading the photo. You can use any name for your client that you want.

Upload new photo without metadata

To send a photo without its associated metadata, post to the following URL:

https://picasaweb.google.com/data/feed/api/user/username/albumid/albumid

This can be done using the following code:

MediaFileSource myMedia = new MediaFileSource(new File("/home/liz/puppies.jpg"), "image/jpeg");
PhotoEntry returnedPhoto = myService.insert(feedUrl, PhotoEntry.class, myMedia);

If you want to post a photo, but don't want the hassle of requiring the user of your app to choose an album, you can post the photo to the 'Drop Box.' This special album will automatically be created the first time it is used to store a photo. To post to the 'Drop Box,' use an albumid value of default.

Upload a video

Uploading a video can be done in the same way as uploading a photo with metadata:

URL albumPostUrl = new URL("https://picasaweb.google.com/data/feed/api/user/username/albumid/albumid");

PhotoEntry myVideo = new PhotoEntry();
myVideo.setTitle(new PlainTextConstruct("birthday.mov"));
myVideo.setDescription(new PlainTextConstruct("My grandpa's 80th birthday."));
myVideo.setClient("myClientName");

MediaFileSource myMedia = new MediaFileSource(new File("/home/liz/birthday.mov"), "video/quicktime");
myVideo.setMediaSource(myMedia);

PhotoEntry returnedVideo = myService.insert(albumPostUrl, myVideo);

// Fetching the video status (will always be "pending" right after posting a video).
String videoStatus = returnedVideo.getVideoStatus();

You can let the video processing service create a video thumbnail automatically or you can provide an image to be used instead.

Improving performance

Some special features are available to help you optimize your Picasa Web Albums Data API requests.

Retrieving specific field (Experimental)

When you use the Java Client Library to work with the Picasa Web Albums Data API, you are actually making underlying requests that transfer XML data using the Google Data Protocol. By default, requests that return data transfer the full representation of the target resource. Yet receiving full responses to requests can consume a lot of network and CPU resources, especially when you're making many requests. To reduce resource use, you can request that the server return only certain fields for each returned event.

To request only parts of an album instead of the full album, use the Query.setFields method. For more information, including the field-specification syntax, see the partial-response documentation.

For example, the following code retrieves the title, ID, and location fields for each of the user's albums, using a partial request.

String albumsUrl = "https://picasaweb.google.com/data/feed/api/user/username";

// Selection criteria to fetch only title, gphoto:id, and gphoto:location fields for each album.
String fields = "entry(title,gphoto:id,gphoto:location)";

Query albumQuery = new Query(new URL(albumsUrl));
albumQuery.setFields(fields);

AlbumFeed partialFeed = service.query(albumQuery, AlbumFeed.class);
for (GphotoEntry partialEntry : partialFeed.getEntries()) {
  if (partialEntry instanceof AlbumEntry) {
    AlbumEntry partialAlbumEntry = (AlbumEntry) partialEntry;
    System.out.println(String.format("%s: [title - %s, location - %s]", partialAlbumEntry.getGphotoId(), partialAlbumEntry.getTitle().getPlainText(), partialAlbumEntry.getLocation()));
  }
}

Note: The fields you specify with the Query.setFields method are expressed in terms of the Google Data Protocol's AtomPub XML representation for the Picasa Web Albums Data API. For more information about these fields, see the protocol and the element reference documentation.

Conclusion

Hopefully, you now have a good idea of how to get started using the Picasa Web Albums API! If you have questions, comments, or noticed a typo in this document, let us know in the forum.

Back to top