My favorites | English | Sign in

Google Book Search APIs (Labs)

Data API: Developer's Guide, Java

The Google Book Search Data API allows client applications to view and update Book Search content in the form of Google Data API feeds.

Your client application can use the Book Search Data API to issue full-text searches for books and to retrieve standard book information, ratings, and reviews. You can also access individual users' library collections and public reviews. Finally, your application can submit authenticated requests to enable users to create and modify library collections, ratings, labels, reviews, and other account-specific entities.

In addition to providing some background on the capabilities of the Book Search Data API, this document provides examples of basic Data API interactions using the Java client library. If you're interested in understanding more about the underlying protocol that the library uses, see the Protocol section of this developer's guide.

Contents

Audience

This document is intended for programmers who want to write Java client applications that can interact with Google Book Search.

This document assumes that you understand the general ideas behind the Google Data APIs protocol, and that you're familiar with Google Book Search and its My Library features.

For reference information about the classes and methods provided by the client library, see the Java client library API reference.

For general Book Search Data API reference information, see the Protocol reference guide.

Getting started

For help setting up the client library, see the Getting Started Guide.

The Java client library requires Java 1.5. After downloading the client library, you'll find the classes you need to get started in the java/lib/gdataclient-1.0.jar file.

Creating a Book Search account

For testing purposes, you may want to create a Book Search library. Book Search uses Google Accounts, so if you already have a Google account, you can use the My Library features with that account.

Running the sample code

A full working sample client, containing all the sample code shown in this document, is available in the Java client library distribution, under the directory gdata/java/sample/books/BooksClient.java. Build and execution instructions are included in the same directory in the README.txt file.

The sample client performs several operations on the default BooksService to demonstrate the use of the Book Search Data API.

To compile the examples in this document into your own code, you'll need the following import statements:

import com.google.gdata.client.*;
import com.google.gdata.client.books.*;
import com.google.gdata.data.*;
import com.google.gdata.data.books.*;
import com.google.gdata.data.dublincore.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.URL;

Authenticating to the Book Search service

You can access both public and private feeds using the Book Search Data API. Public feeds don't require any authentication, but they are read-only. If you want to modify user libraries, submit reviews or ratings, or add labels, then your client needs to authenticate before requesting private feeds. It can authenticate using either of two approaches: AuthSub proxy authentication or ClientLogin username/password authentication.

For more information about authentication with Google Data APIs in general, see the authentication documentation.

Most of the samples in subsequent sections of this document assume you have an authenticated BooksService object.

AuthSub proxy authentication

AuthSub proxy authentication is used by web applications that need to authenticate their users to Google Accounts. The website operator and the client code don't have access to the username and password for the Book Search user; instead, the client obtains special AuthSub tokens that allow the client to act on a particular user's behalf. For more detailed information, see the AuthSub documentation.

When a user first visits your application, they have not yet been authenticated. In this case, you need to display some information and a link directing the user to a Google page to authenticate your request for access to their account. The Java client library provides a function to generate the Google page's URL. The code below retrieves the URL of the AuthSubRequest page:

String next = "http://www.example.com/welcome.html";
String scope = "http://www.google.com/books/feeds";
boolean secure = false;
boolean session = true;
String authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure, session);

The getRequestUrl method takes the following parameters (corresponding to the query parameters used by the AuthSubRequest handler):

next
The URL of the page that Google should redirect the user to after authentication.
scope
Indicates that the application is requesting a token to access Book Search feeds. The scope string to use is http://www.google.com/books/feeds/ (URL-encoded, of course).
secure
Indicates whether the client is requesting a secure token.
session
Indicates whether the token returned can be exchanged for a multi-use (session) token.

The above example shows a call that doesn't request a secure token (the value of secure is false). The resulting request URL might look like this:

https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fwww.google.com%2Fbooks%2Ffeeds%2F&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2Fwelcome.html

The user follows the link to Google's site and authenticates to their Google Account.

After the user authenticates, the AuthSub system redirects them to the URL you specified in the next query parameter of the AuthSubRequest URL. The AuthSub system appends an authentication token to that URL, as the value of the token query parameter. For example:

http://www.example.com/welcome.html?token=yourAuthToken

This token value represents a single-use AuthSub token. In this example, since session = true was specified, this token can be exchanged for an AuthSub session token by calling the AuthSubSessionToken service, as follows, where urlFromAuthSub is the URL that AuthSub appended the token to:

String token = AuthSubUtil.getTokenFromReply(urlFromAuthSub);
String sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

That is, you pass your one-time-use token to the exchangeForSessionToken method, along with either null (for unregistered mode) or a private key (for registered mode), and the AuthSub interface returns a session token. For more information about registered applications and private keys, see the "Signing requests" section of the AuthSub documentation.

Your application can then use the session token value in subsequent interactions with Book Search. The client library automatically sends the token along with requests.

ClientLogin username/password authentication

Use ClientLogin authentication if your client is a standalone, single-user "installed" client (such as a desktop application). Just call the setUserCredentials method on your BooksService object and all subsequent interactions with Book Search will be authenticated:

BooksService myService = new BooksService("exampleCo-exampleApp-1");
myService.setUserCredentials("user@domain.com", "secretPassword");

In the snippet above, we pass one parameter to the BooksService constructor: the name of our application in the form companyName-applicationName-versionNumber.

For more information about ClientLogin authentication, including sample requests and responses, see the Authentication for Installed Applications documentation.

Note: Use the same token for all requests in a given session; don't acquire a new token for each Book Search request.

Searching for books

The Book Search Data API provides a number of feeds that list collections of books.

The most common action is to retrieve a list of books that match a search query. To do so you create a VolumeQuery object and pass it to the BooksService.

For example, to perform a keyword query, with a filter on viewability to restrict the results to partial or full view books, use the setMinViewability and setFullTextQuery methods of the VolumeQuery object. The following code snippet prints the title and viewability of all volumes whose metadata or text matches the query term "domino":

VolumeQuery query = new VolumeQuery(new URL("http://www.google.com/books/feeds/volumes"));

// exclude no-preview books (by default, they are included)
query.setMinViewability(VolumeQuery.MinViewability.PARTIAL);

// search for "domino"
query.setFullTextQuery("domino");

VolumeFeed volumeFeed = service.query(query, VolumeFeed.class);

// print title(s) and viewability value if available
for(VolumeEntry entry : volumeFeed.getEntries() ) {
  for (Title t : entry.getTitles()) {
    System.out.print(t.getValue() + "\t");
  }
  System.out.println("Viewability: " + entry.getViewability().getValue());
}

The Query class, and subclasses like VolumeQuery, are responsible for constructing feed URLs. The VolumeQuery shown above constructs a URL equivalent to the following:

http://www.google.com/books/feeds/volumes?q=keyword&min-viewability=partial

Note: Since Book Search results are public, you can issue a Book Search query without authentication.

Here are some of the most common VolumeQuery methods for setting search parameters:

setFullTextQuery
Specifies a search query term. Book Search searches all book metadata and full text for books matching the term. Book metadata includes titles, keywords, descriptions, author names, and subjects.

Note that any spaces, quotes or other punctuation in the parameter value must be URL-escaped. (Use a plus (+) for a space.)

To search for an exact phrase, enclose the phrase in quotation marks. For example, to search for books matching the phrase "spy plane", set the q parameter to %22spy+plane%22.

You can also use any of the advanced search operators supported by Book Search. For example, jane+austen+-inauthor:austen returns matches that mention (but are not authored by) Jane Austen.
setStartIndex
Specifies the index of the first matching result that should be included in the result set. This parameter uses a one-based index, meaning the first result is 1, the second result is 2 and so forth. This parameter works in conjunction with the max-results parameter to determine which results to return. For example, to request the third set of 10 results—results 21-30—set the start-index parameter to 21 and the max-results parameter to 10.

Note: This isn't a general cursoring mechanism. If you first send a query with ?start-index=1&max-results=10 and then send another query with ?start-index=11&max-results=10, the service cannot guarantee that the results are equivalent to ?start-index=1&max-results=20, because insertions and deletions could have taken place in between the two queries.

setMaxResults
Specifies the maximum number of results that should be included in the result set. This parameter works in conjunction with the start-index parameter to determine which results to return. The default value of this parameter is 10 and the maximum value is 20.
setMinViewability
Allows you to filter the results according to the books' viewability status. This parameter accepts one of three values: NONE (the default, returning all matching books regardless of viewability), PARTIAL (returning only books that the user can preview or view in their entirety), or FULL (returning only books that the user can view in their entirety).

Note that these search query parameters can also be set for other types of feed requests. For example, as described in the Searching for books in a user's library section, you can retrieve books in a specific user's library that match a particular keyword.

Partner Co-Branded Search

Google Book Search provides Co-Branded Search, which lets content partners provide full-text search of their books from their own websites.

If you are a partner who wants to do Co-Branded Search using the Book Search Data API, you may do so by modifying the feed URL above to point to your Co-Branded Search implementation. If, for example, a Co-Branded Search is available at the following URL:

http://books.google.com/books/p/PARTNER_COBRAND_ID?q=football

then you can obtain the same results using the Book Search Data API at the following URL:

http://www.google.com/books/feeds/p/PARTNER_COBRAND_ID/volumes?q=football+-soccer

For additional information or support, visit our Partner help center.

Using community features

Adding a rating

A user can add a rating to a book. Book Search uses a 1-5 rating system in which 1 is the lowest rating. Users cannot update or delete ratings.

To add a rating, add a Rating object to a VolumeEntry and post it to the annotation feed. In the example below, we start from an empty VolumeEntry object.

VolumeEntry newEntry = new VolumeEntry();
newEntry.setId(VOLUME_ID);
Rating myRating = new Rating();
myRating.setValue(4);
myRating.setMax(5);
myRating.setMin(1);
entry.setRating(myRating);
service.insert(new URL("http://www.google.com/books/feeds/users/me/volumes"), entry);

Reviews

In addition to ratings, authenticated users can submit reviews or edit their reviews. For information on how to request previously submitted reviews, see Retrieving annotations.

Adding a review

To add a review, add a Review object to a VolumeEntry and post it to the annotation feed. In the example below, we start from an existing VolumeEntry object.

String annotationUrl = entry.getAnnotationLink().getHref();
Review myReview = new Review();
myReview.setValue("This book is amazing!");
entry.setReview(myReview);
service.insert(new URL(annotationUrl), entry);

Editing a review

To update an existing review, first you retrieve the review you want to update, then you modify it, and then you submit it to the annotation feed.

String entryUrl = entry.getId();
Review myReview = entry.getReview();
myReview.setValue("This book is actually not that good!");
entry.setReview(myReview);
service.update(new URL(entryUrl), entry);

Labels

You can use the Book Search Data API to label volumes with keywords. A user can submit, retrieve and modify labels. See Retrieving annotations for how to read previously submitted labels.

Submitting a set of labels

To submit labels, add a Category object with the scheme LABELS_SCHEME to a VolumeEntry and post it to the annotation feed.

String annotationUrl = entry.getAnnotationLink().getHref();
entry.getCategories().add(
  new Category(BooksCategory.Scheme.LABELS_SCHEME, "science-fiction"));
entry.getCategories().add(
  new Category(BooksCategory.Scheme.LABELS_SCHEME, "favorite"));
service.insert(new URL(annotationUrl), entry);

Editing labels

To update existing labels, first you retrieve the entry with the labels you want to update, then you modify or delete them, and then you send the modified entry to the annotation feed.

String entryUrl = entry.getId();
entry.getCategories().clear();
entry.getCategories().add(
  new Category(BooksCategory.Scheme.LABELS_SCHEME, "pink cover"));
service.update(new URL(entryUrl), entry);

Retrieving annotations: reviews, ratings, and labels

You can use the Book Search Data API to retrieve annotations submitted by a given user. Annotations include reviews, ratings, and labels. To retrieve any user's annotations, you can send an unauthenticated request that includes the user's user ID. To retrieve the authenticated user's annotations, use the value me as the user ID.

VolumeQuery query = new VolumeQuery(
    new URL("http://www.google.com/books/feeds/users/USER_ID/volumes"));
VolumeFeed volumeFeed = service.query(query, VolumeFeed.class);

// print title(s) and viewability value if available
for(VolumeEntry entry : volumeFeed.getEntries() ) {
  for (Title t : entry.getTitles()) {
    System.out.println(t.getValue() + "\t");
  }
  if (entry.hasRating()) {
    System.out.println("Rating: " + entry.getRating().getValue());
  }
}

For a list of the supported query parameters, see the query parameters section.

Deleting Annotations

If you retrieved an annotation entry containing ratings, reviews, and/or labels, you can remove all annotations by calling delete on that entry.

annotationEntry.delete();

Book collections and My Library

Google Book Search provides a number of user-specific book collections, each of which has its own feed.

The most important collection is the user's My Library, which represents the books the user would like to remember, organize, and share with others. This is the collection the user sees when accessing his or her My Library page.

Retrieving books in a user's library

The following sections describe how to retrieve a list of books from a user's library, with or without query parameters.

You can query a Book Search public feed without authentication.

Retrieving all books in a user's library

To retrieve the user's books, send a query to the My Library feed. To get the library of the authenticated user, use me in place of USER_ID.

VolumeQuery query = new VolumeQuery(
    new URL("http://www.google.com/books/feeds/users/USER_ID/collections/library/volumes"));
VolumeFeed volumeFeed = service.query(query, VolumeFeed.class);

Note: The feed may not contain all of the user's books, because there's a default limit on the number of results returned. For more information, see the max-results query parameter in Searching for books.

Searching for books in a user's library

Just as you can search across all books, you can do a full-text search over just the books in a user's library. To do this, just set the appropriate paramters on the VolumeQuery object.

For example, the following query returns all the books in your library that contain the word "bear":

VolumeQuery query = new VolumeQuery(
    new URL("http://www.google.com/books/feeds/users/USER_ID/collections/library/volumes"));
query.setFullTextQuery("bear");
VolumeFeed volumeFeed = service.query(query, VolumeFeed.class);

For a list of the supported query parameters, see the query parameters section. In addition, you can search for books that have been labeled by the user:

VolumeQuery query = new VolumeQuery(
    new URL("http://www.google.com/books/feeds/users/USER_ID/collections/library/volumes"));
CategoryFilter filter = new CategoryFilter();;
filter.addCategory(
    new Category(BooksCategory.Scheme.LABELS_SCHEME, "favorite"));
query.addCategoryFilter(filter);
VolumeFeed volumeFeed = service.query(query, VolumeFeed.class);

Updating books in a user's library

You can use the Book Search Data API to add a book to, or remove a book from, a user's library. Ratings, reviews, and labels are valid across all the collections of a user, and are thus edited using the annotation feed (see Using community features).

Adding a book to a library

After authenticating, you can add books to the current user's library.

You can either create an entry from scratch if you know the volume ID, or insert an entry read from any feed.

The following example creates a new entry and adds it to the library:

VolumeEntry newEntry = new VolumeEntry();
newEntry.setId(VOLUME_ID);
service.insert(
    new URL("http://www.google.com/books/feeds/users/USER_ID/collections/library/volumes"), newEntry);

The following example adds an existing VolumeEntry object to the library:

service.insert(
    new URL("http://www.google.com/books/feeds/users/USER_ID/collections/library/volumes"), entry);

The user ID must be the ID of the authenticated user, or else the keyword me.

Removing a book from a library

To remove a book from a user's library, call delete on the VolumeEntry object.

entry.delete();