Batching API Calls

As well as executing requests immediately, it is also possible to batch up several requests to be sent in a single network call. This is accomplished using the Google_Http_Batch class, and by setting the useBatch parameter on the Google_Client to true.

Batching Requests

Setting useBatch to true causes requests to return the query, rather than immediately executing it. These requests can be added to the batch, which can be executed directly.


$client->setUseBatch(true);
$batch = new Google_Http_Batch($client);

$optParams = array('filter' => 'free-ebooks');
$req1 = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
$batch->add($req1, "thoreau");
$req2 = $service->volumes->listVolumes('George Bernard Shaw', $optParams);
$batch->add($req2, "shaw");

$results = $batch->execute();
    

Handling Responses

All results are returned as a single array. Each individual result set is available under the key set as the second parameter when adding the request to the batch, prefixed with response-. So in this case the request key shaw becomes response-shaw.


echo "<h3>Results Of Call 1:</h3>";
foreach ($results['response-thoreau'] as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}
echo "<h3>Results Of Call 2:</h3>";
foreach ($results['response-shaw'] as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}