Picasa Web Albums allows client applications to view and update albums, photos, and comments in the form of Google Data API feeds. Your client application can use the Picasa Web Albums Data API to create new albums, upload photos, add comments, edit or delete existing albums, photos, and comments, 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, please see the protocol guide.
Contents
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, deletes, or updates).
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:
- Construct the AuthSub URL.
- Send the user to a Google page to enter their AuthSub credentials.
- When the user returns, acquire a session token.
- Create a
PicasawebService
object.
- 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:
http://picasaweb.google.com/data/
It'll look something like this:
String requestUrl =
AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
"http://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, update, or delete 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("http://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.
Add an album
AlbumEntry myAlbum = new AlbumEntry();
myAlbum.setTitle(new PlainTextConstruct("Trip to France"));
myAlbum.setDescription(new PlainTextConstruct("My recent trip to France was delightful!"));
AlbumEntry insertedEntry = myService.insert(postUrl, myAlbum);
The above code creates a new AlbumEntry
, then sets various attributes for the album (title and description). It assumes that myService
is an authenticated PicasawebService
object. myService
then calls the insert
method to add the album and receive the response. If an error occurs during the insertion, then the client library generates an appropriate exception, so your code should be prepared to handle exceptions.
Modify the properties of an album
Once an entry is retrieved, it can be easily modified using the update
method.
myAlbum.setDescription(new PlainTextConstruct("Updated album description"));
myAlbum.update();
Delete an album
Retrieved entries can also be deleted using the delete
method.
myAlbum.delete();
Working with Photos
When uploading, modifying, or removing photos, you will 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, or search photos from the public albums of other users.
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 = "http://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("http://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());
}
With the API, you can search photos uploaded by other users, as long as they are in a public album. The following code retrieves 10 photos matching a search for "puppy," (because who doesn't love puppies?) and prints out their titles. We'll illustrate this operation using a Query
object. All the parameters previously specified are set — 10 results and "puppy" as a search term.
URL baseSearchUrl = new URL("http://picasaweb.google.com/data/feed/api/all");
Query myQuery = new Query(baseSearchUrl);
myQuery.setStringCustomParameter("kind", "photo");
myQuery.setMaxResults(10);
myQuery.setFullTextQuery("puppy");
AlbumFeed searchResultsFeed = myService.query(myQuery, AlbumFeed.class);
for (PhotoEntry photo : searchResultsFeed.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
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 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("http://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.
To send a photo without its associated metadata, post to the following URL:
http://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("http://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. In the following sample, the returnedVideo
variable from the above sample is used to update the thumbnail for the video:
MediaFileSource myThumb = new MediaFileSource(new File("/home/liz/birthday_title.jpg"), "image/jpeg");
returnedVideo.setMediaSource(myThumb);
PhotoEntry updatedEntry = returnedVideo.updateMedia(false);
Note: updating the entire video media data is currently not supported. You will have to create a new video entry and delete the existing one.
Update a photo
This example will update the photo's a title, tags, and geographic location. Notice that we are adding three tags (foo, bar, and baz) all at the same time using the <media:keywords>
element.
myPhoto.setTitle(new PlainTextConstruct("New Title"));
MediaKeywords myTags = new MediaKeywords();
myTags.addKeyword("cute, puppy, dog");
myPhoto.setKeywords(tags);
myPhoto.setGeoLocation(37.7733, -122.4178);
myPhoto.update();
Delete a photo
Deleting a photo is done by using the delete
method, after you have retrieved the photo object.
myPhoto.delete();
Tags are a convenient way to label and organize your photos. By associating photos with descriptive strings, it makes searching through large quantities of photos easier.
Your program can retrieve a list of tags that are used by a user, in a particular album, or that are associated with a particular photo.
The following code will print out all of the tags that username
has used in photos in their albums.
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 = new URL("http://picasaweb.google.com/data/feed/api/user/username?kind=tag");
AlbumFeed searchResultsFeed = myService.query(feedUrl, AlbumFeed.class);
for (TagEntry tag : searchResultsFeed.getTagEntries()) {
System.out.println(tag.getTitle().getPlainText());
}
The following code will print out all of the tags that username
has tagged photos with in the albumid
album.
URL feedUrl = new
URL("http://picasaweb.google.com/data/feed/api/user/username/albumid/albumid?kind=tag");
AlbumFeed searchResultsFeed = myService.query(feedUrl, AlbumFeed.class);
for (TagEntry tag : searchResultsFeed.getTagEntries()) {
System.out.println(tag.getTitle().getPlainText());
}
The following code will print out all of the tags that username
has tagged on the photo identified by photoid
within the albumid
album. The Accessing photo information section describes how to retrieve a valid value for photoid
.
URL feedUrl = new
URL("http://picasaweb.google.com/data/feed/api/user/username/albumid/albumid/photoid/photoid?kind=tag");
AlbumFeed searchResultsFeed = myService.query(feedUrl, AlbumFeed.class);
for (TagEntry tag : searchResultsFeed.getTagEntries()) {
System.out.println(tag.getTitle().getPlainText());
}
Note that this same information is available inside of the <media:keywords>
element of the photo itself in a comma separated format.
The following code uses the tag
parameter to search for all photos belonging to username
that are tagged with "puppy."
Here, we're creating a Query object and setting the tag to search for and the photo kind
.
URL feedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/username");
Query myQuery = new Query(feedUrl);
myQuery.setStringCustomParameter("kind", "photo");
myQuery.setStringCustomParameter("tag", "puppy");
AlbumFeed searchResultsFeed = myService.query(myQuery, AlbumFeed.class);
for (PhotoEntry photo : searchResultsFeed.getPhotoEntries()) {
System.out.println(photo.getTitle().getPlainText());
}
Note that you could search for photos in a particular album by adding the albumid in the URL.
The following code adds the tag "terrier" to the photo identified by photoid
, in the albumid
album, which is owned by username
.
URL feedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/username/albumid/albumid/photoid/photoid");
TagEntry myTag = new TagEntry();
myTag.setTitle(new PlainTextConstruct("terrier"));
myService.insert(feedUrl, myTag);
Note that this can also be done in bulk as described in the Update a photo section using the <media:keywords>
element.
Deleting a tag is done by using the delete
method on the tag entry.
myTag.delete();
Comments are short text snippets attached to photos by Picasa Web Albums users.
The following example prints out the most recent comments on username
's photos.
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 = new URL("http://picasaweb.google.com/data/feed/api/user/username?kind=comment");
AlbumFeed myFeed = myService.query(myQuery, AlbumFeed.class);
for(PhotoEntry comment : feed.getPhotoEntries()) {
System.out.println(comment.getTitle().getPlainText());
}
You can also retrieve all of the comments associated with a particular photo. The following example prints out all of the comments on the photo identified by photoid
, inside of the albumid
album, owned by the username
user. The Accessing photo information section describes how to retrieve a valid value for photoid
.
URL feedUrl = new
URL("http://picasaweb.google.com/data/feed/api/user/username/albumid/albumid/photoid/photoid?kind=comment");
PhotoFeed searchResultsFeed = myService.getFeed(feedUrl, PhotoFeed.class);
for (CommentEntry comment : searchResultsFeed.getCommentEntries()) {
System.out.println(comment.getPlainTextContent());
}
The following code adds the comment "great photo!" to the photo identified by photoid
in the albumid
owned by username
.
URL feedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/username/albumid/albumid/photoid/photoid");
CommentEntry myComment = new CommentEntry();
myComment.setContent(new PlainTextConstruct("great photo!"));
myService.insert(feedUrl, myComment);
Deleting a comment is done by using the delete
method.
myComment.delete();
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 = "http://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, please see the protocol and the element reference documentation.
Updating specific fields (Experimental )
When you change a field in a local copy of an album, you can send the server just the updated field, rather than sending the entire updated entry. For more information, see the partial-update documentation.
The following code updates an album's location using partial update. In this example we are updating the gphoto:location
for one of the albums retrieved using partial response.
String albumEntryUrl = "http://picasaweb.google.com/data/feed/api/user/username/albumid";
// Retrieve only the ETag and location attributes for the album to be updated.
String fields = "@gd:etag,gphoto:location";
Query patchQuery = new Query(new URL(albumEntryUrl));
patchQuery.setFields(fields);
AlbumEntry partialEntry = service.getEntry(patchQuery.getUrl(), AlbumEntry.class);
System.out.println("Current location: " + partialEntry.getLocation());
// Update the location in the album entry.
partialEntry.setLocation(newLocation);
AlbumEntry updated = service.patch(new URL(albumEntryUrl), fields, partialEntry);
System.out.println("Location set to: " + updated.getLocation());
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.
http://code.google.com/apis/picasaweb/docs/2.0/developers_guide_java.html