Using Google Base

The Google Base data API is designed to enable developers to do two things:

  • Query Google Base data to create applications and mashups.

  • Input and manage Google Base items programmatically.

There are two item feeds: snippets feed and customer items feeds. The snippets feed contains all Google Base data and is available to anyone to query against without a need for authentication. The customer items feed is a customer-specific subset of data and only a customer/owner can access this feed to insert, update, or delete their own data. Queries are constructed the same way against both types of feeds.

See » http://code.google.com/apis/base for more information about the Google Base API.

Connect To The Base Service

The Google Base API, like all GData APIs, is based off of the Atom Publishing Protocol (APP), an XML based format for managing web-based resources. Traffic between a client and the Google Base servers occurs over HTTP and allows for both authenticated and unauthenticated connections.

Before any transactions can occur, this connection needs to be made. Creating a connection to the base servers involves two steps: creating an HTTP client and binding a Zend_Gdata_Gbase service instance to that client.

Authentication

The Google Base API allows access to both public and private base feeds. Public feeds do not require authentication, but are read-only and offer reduced functionality. Private feeds offers the most complete functionality but requires an authenticated connection to the base servers. There are three authentication schemes that are supported by Google Base:

  • ClientAuth provides direct username/password authentication to the base servers. Since this scheme requires that users provide your application with their password, this authentication is only recommended when other authentication schemes are insufficient.

  • AuthSub allows authentication to the base servers via a Google proxy server. This provides the same level of convenience as ClientAuth but without the security risk, making this an ideal choice for web-based applications.

The Zend_Gdata library provides support for all three authentication schemes. The rest of this chapter will assume that you are familiar the authentication schemes available and how to create an appropriate authenticated connection. For more information, please see the authentication section or the » Authentication Overview in the Google Data API Developer's Guide.

Create A Service Instance

In order to interact with Google Base, this library provides the Zend_Gdata_Gbase service class. This class provides a common interface to the Google Data and Atom Publishing Protocol models and assists in marshaling requests to and from the base servers.

Once deciding on an authentication scheme, the next step is to create an instance of Zend_Gdata_Gbase. This class takes in an instance of Zend_Http_Client as a single argument. This provides an interface for AuthSub and ClientAuth authentication, as both of these creation of a special authenticated HTTP client. If no arguments are provided, an unauthenticated instance of Zend_Http_Client will be automatically created.

The example below shows how to create a Base service class using ClientAuth authentication:

  1. // Parameters for ClientAuth authentication
  2. $service = Zend_Gdata_Gbase::AUTH_SERVICE_NAME;
  3. $user = "sample.user@gmail.com";
  4. $pass = "pa$$w0rd";
  5.  
  6. // Create an authenticated HTTP client
  7. $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
  8.  
  9. // Create an instance of the Base service
  10. $service = new Zend_Gdata_Gbase($client);

A Base service using AuthSub can be created in a similar, though slightly more lengthy fashion:

  1. /*
  2. * Retrieve the current URL so that the AuthSub server knows where to
  3. * redirect the user after authentication is complete.
  4. */
  5. function getCurrentUrl()
  6. {
  7.     global $_SERVER;
  8.  
  9.     // Filter php_self to avoid a security vulnerability.
  10.     $php_request_uri =
  11.         htmlentities(substr($_SERVER['REQUEST_URI'],
  12.                             0,
  13.                             strcspn($_SERVER['REQUEST_URI'], "\n\r")),
  14.                      ENT_QUOTES);
  15.  
  16.     if (isset($_SERVER['HTTPS']) &&
  17.         strtolower($_SERVER['HTTPS']) == 'on') {
  18.         $protocol = 'https://';
  19.     } else {
  20.         $protocol = 'http://';
  21.     }
  22.     $host = $_SERVER['HTTP_HOST'];
  23.     if ($_SERVER['HTTP_PORT'] != '' &&
  24.         (($protocol == 'http://' && $_SERVER['HTTP_PORT'] != '80') ||
  25.         ($protocol == 'https://' && $_SERVER['HTTP_PORT'] != '443'))) {
  26.         $port = ':' . $_SERVER['HTTP_PORT'];
  27.     } else {
  28.         $port = '';
  29.     }
  30.     return $protocol . $host . $port . $php_request_uri;
  31. }
  32.  
  33. /**
  34. * Obtain an AuthSub authenticated HTTP client, redirecting the user
  35. * to the AuthSub server to login if necessary.
  36. */
  37. function getAuthSubHttpClient()
  38. {
  39.     global $_SESSION, $_GET;
  40.  
  41.     // If there is no AuthSub session or one-time token waiting for us,
  42.     // redirect the user to the AuthSub server to get one.
  43.     if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
  44.         // Parameters to give to AuthSub server
  45.         $next = getCurrentUrl();
  46.         $scope = "http://www.google.com/base/feeds/items/";
  47.         $secure = false;
  48.         $session = true;
  49.  
  50.         // Redirect the user to the AuthSub server to sign in
  51.  
  52.         $authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($next,
  53.                                                              $scope,
  54.                                                              $secure,
  55.                                                              $session);
  56.          header("HTTP/1.0 307 Temporary redirect");
  57.  
  58.          header("Location: " . $authSubUrl);
  59.  
  60.          exit();
  61.     }
  62.  
  63.     // Convert an AuthSub one-time token into a session token if needed
  64.     if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
  65.         $_SESSION['sessionToken'] =
  66.             Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
  67.     }
  68.  
  69.     // At this point we are authenticated via AuthSub and can obtain an
  70.     // authenticated HTTP client instance
  71.  
  72.     // Create an authenticated HTTP client
  73.     $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
  74.     return $client;
  75. }
  76.  
  77. // -> Script execution begins here <-
  78.  
  79. // Make sure http://code.google.com/apis/gdata/reference.html#Queriesthat
  80. // the user has a valid session, so we can record the
  81. // AuthSub session token once it is available.
  82.  
  83. // Create an instance of the Base service, redirecting the user
  84. // to the AuthSub server if necessary.
  85. $service = new Zend_Gdata_Gbase(getAuthSubHttpClient());

Finally, an unauthenticated server can be created for use with snippets feeds:

  1. // Create an instance of the Base service using an unauthenticated HTTP client
  2. $service = new Zend_Gdata_Gbase();

Retrieve Items

You can query customer items feed or snippets feed to retrieve items. It involves two steps, sending a query and iterating through the returned feed.

Send a Structured Query

You can send a structured query to retrieve items from your own customer items feed or from the public snippets feed.

When retrieving items using the Base API, specially constructed query URLs are used to describe what events should be returned. The Zend_Gdata_Gbase_ItemQuery and Zend_Gdata_Gbase_SnippetQuery classes simplify this task by automatically constructing a query URL based on provided parameters.

Query Customer Items Feed

To execute a query against the customer items feed, invoke newItemQuery() and getGbaseItemFeed() methods:

  1. $service = new Zend_Gdata_Gbase($client);
  2. $query = $service->newItemQuery();
  3. $query->setBq('[title:Programming]');
  4. $query->setOrderBy('modification_time');
  5. $query->setSortOrder('descending');
  6. $query->setMaxResults('5');
  7. $feed = $service->getGbaseItemFeed($query);

A full list of these parameters is available at the » Query parameters section of the Customer Items Feed documentation.

Query Snippets Feed

To execute a query against the public snippets feed, invoke newSnippetQuery() and getGbaseSnippetFeed() methods:

  1. $service = new Zend_Gdata_Gbase();
  2. $query = $service->newSnippetQuery();
  3. $query->setBq('[title:Programming]');
  4. $query->setOrderBy('modification_time');
  5. $query->setSortOrder('descending');
  6. $query->setMaxResults('5');
  7. $feed = $service->getGbaseSnippetFeed($query);

A full list of these parameters is available at the » Query parameters section of the Snippets Feed documentation.

Iterate through the Items

Google Base items can contain item-specific attributes such as <g:main_ingredient> and <g:weight>.

To iterate through all attributes of a given item, invoke getGbaseAttributes() and iterate through the results:

  1. foreach ($feed->entries as $entry) {
  2.   // Get all attributes and print out the name and text value of each
  3.   // attribute
  4.   $baseAttributes = $entry->getGbaseAttributes();
  5.   foreach ($baseAttributes as $attr) {
  6.     echo "Attribute " . $attr->name . " : " . $attr->text . "<br>";
  7.   }
  8. }

Or, you can look for specific attribute name and iterate through the results that match:

  1. foreach ($feed->entries as $entry) {
  2.   // Print all main ingredients <g:main_ingredient>
  3.   $baseAttributes = $entry->getGbaseAttribute("main_ingredient");
  4.   foreach ($baseAttributes as $attr) {
  5.     echo "Main ingredient: " . $attr->text . "<br>";
  6.   }
  7. }

Insert, Update, and Delete Customer Items

A customer/owner can access his own Customer Items feed to insert, update, or delete their items. These operations do not apply to the public snippets feed.

You can test a feed operation before it is actually executed by setting the dry-run flag ($dryRun) to TRUE. Once you are sure that you want to submit the data, set it to FALSE to execute the operation.

Insert an Item

Items can be added by using the insertGbaseItem() method for the Base service:

  1. $service = new Zend_Gdata_Gbase($client);
  2. $newEntry = $service->newItemEntry();
  3.  
  4. // Add title
  5. $title = "PHP Developer Handbook";
  6. $newEntry->title = $service->newTitle(trim($title));
  7.  
  8. // Add some content
  9. $content = "Essential handbook for PHP developers.";
  10. $newEntry->content = $service->newContent($content);
  11. $newEntry->content->type = 'text';
  12.  
  13. // Define product type
  14. $itemType = "Products";
  15. $newEntry->itemType = $itemType;
  16.  
  17. // Add item specific attributes
  18. $newEntry->addGbaseAttribute("product_type", "book", "text");
  19. $newEntry->addGbaseAttribute("price", "12.99 USD", "floatUnit");
  20. $newEntry->addGbaseAttribute("quantity", "10", "int");
  21. $newEntry->addGbaseAttribute("weight", "2.2 lbs", "numberUnit");
  22. $newEntry->addGbaseAttribute("condition", "New", "text");
  23. $newEntry->addGbaseAttribute("author", "John Doe", "text");
  24. $newEntry->addGbaseAttribute("edition", "First Edition", "text");
  25. $newEntry->addGbaseAttribute("pages", "253", "number");
  26. $newEntry->addGbaseAttribute("publisher", "My Press", "text");
  27. $newEntry->addGbaseAttribute("year", "2007", "number");
  28. $newEntry->addGbaseAttribute("payment_accepted", "Google Checkout", "text");
  29.  
  30. $dryRun = true;
  31. $createdEntry = $service->insertGbaseItem($newEntry, $dryRun);

Modify an Item

You can update each attribute element of an item as you iterate through them:

  1. // Update the title
  2. $newTitle = "PHP Developer Handbook Second Edition";
  3. $entry->title = $service->newTitle($newTitle);
  4.  
  5. // Find <g:price> attribute and update the price
  6. $baseAttributes = $entry->getGbaseAttribute("price");
  7. if (is_object($baseAttributes[0])) {
  8.   $newPrice = "16.99 USD";
  9.   $baseAttributes[0]->text = $newPrice;
  10. }
  11.  
  12. // Find <g:pages> attribute and update the number of pages
  13. $baseAttributes = $entry->getGbaseAttribute("pages");
  14. if (is_object($baseAttributes[0])) {
  15.   $newPages = "278";
  16.   $baseAttributes[0]->text = $newPages;
  17.  
  18.   // Update the attribute type from "number" to "int"
  19.   if ($baseAttributes[0]->type == "number") {
  20.     $newType = "int";
  21.     $baseAttributes[0]->type = $newType;
  22.   }
  23. }
  24.  
  25. // Remove <g:label> attributes
  26. $baseAttributes = $entry->getGbaseAttribute("label");
  27. foreach ($baseAttributes as $note) {
  28.   $entry->removeGbaseAttribute($note);
  29. }
  30.  
  31. // Add new attributes
  32. $entry->addGbaseAttribute("note", "PHP 5", "text");
  33. $entry->addGbaseAttribute("note", "Web Programming", "text");
  34.  
  35. // Save the changes by invoking save() on the entry object itself
  36. $dryRun = true;
  37. $entry->save($dryRun);
  38.  
  39. // Or, save the changes by calling updateGbaseItem() on the service object
  40. // $dryRun = true;
  41. // $service->updateGbaseItem($entry, $dryRun);

After making the changes, either invoke save($dryRun) method on the Zend_Gdata_Gbase_ItemEntry object or call updateGbaseItem($entry, $dryRun) method on the Zend_Gdata_Gbase object to save the changes.

Delete an Item

You can remove an item by calling deleteGbaseItem() method:

  1. $dryRun = false;
  2. $service->deleteGbaseItem($entry, $dryRun);

Alternatively, you can invoke delete() on the Zend_Gdata_Gbase_ItemEntry object:

  1. $dryRun = false;
  2. $entry->delete($dryRun);
blog comments powered by Disqus