Java
/**
* Fetches and prints the results of a page of a search using a cache of page tokens.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param query the search query.
* @param pageNumber the number of the page to fetch and print results for.
* @param pageTokens the cache of page tokens to use and update.
*/
private static void fetchAndPrintPageResults(
GoogleAdsClient googleAdsClient,
long customerId,
String query,
int pageNumber,
SortedMap<Integer, String> pageTokens) {
int currentPageNumber;
// There is no need to fetch the pages we already know the page tokens for.
if (pageTokens.containsKey(pageNumber)) {
System.out.println(
"The token of the requested page was cached, we will use it to get the results.");
currentPageNumber = pageNumber;
} else {
System.out.printf(
"The token of the requested page was never cached, we will use the closest page we know"
+ " the token for (page %d) and sequentially get pages from there.%n",
pageTokens.size());
currentPageNumber = pageTokens.lastKey();
}
// Fetches next pages in sequence and caches their tokens until the requested page results
// are returned.
while (currentPageNumber <= pageNumber) {
// Fetches the next page.
System.out.printf("Fetching page %d...%n", currentPageNumber);
SearchGoogleAdsRequest request =
SearchGoogleAdsRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setPageSize(PAGE_SIZE)
.setQuery(query)
.setReturnTotalResultsCount(true)
// Uses the page token cached for the current page number.
.setPageToken(pageTokens.get(currentPageNumber))
.build();
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
SearchPagedResponse response = googleAdsServiceClient.search(request);
cacheNextPageToken(pageTokens, response.getPage(), currentPageNumber + 1);
// Prints only the results for the requested page.
if (currentPageNumber == pageNumber) {
// Prints the results of the requested page.
System.out.printf("Printing results found for page %d:%n", pageNumber);
for (GoogleAdsRow googleAdsRow : response.getPage().getResponse().getResultsList()) {
System.out.printf(
"- Campaign with ID %d and name '%s'.%n",
googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
}
}
currentPageNumber++;
}
}
}
C#
/// <summary>
/// Fetches and prints the results of a page of a search using a cache of page tokens.
/// </summary>
/// <param name="googleAdsService">The Google Ads API Service client.</param>
/// <param name="request">The request.</param>
/// <param name="pageNumber">The number of the page to fetch and print results for.</param>
/// <param name="pageTokens">The cache of page tokens to use and update.</param>
/// <returns></returns>
private static void FetchAndPrintPageResults(GoogleAdsServiceClient googleAdsService,
SearchGoogleAdsRequest request, int pageNumber, Dictionary<int, string> pageTokens)
{
int currentPageNumber = pageNumber;
// There is no need to fetch the pages we already know the page tokens for.
if (pageTokens.ContainsKey(pageNumber - 1))
{
Console.WriteLine("The token of the requested page was cached, we will use it " +
"to get the results.");
currentPageNumber = pageNumber;
}
else
{
Console.WriteLine("The token of the requested page was never cached, we will " +
$"use the closest page we know the token for (page #{pageNumber}) and " +
$"sequentially get pages from there.");
currentPageNumber = pageNumber;
while (!pageTokens.ContainsKey(currentPageNumber))
{
currentPageNumber--;
}
}
SearchGoogleAdsResponse response = null;
// Fetches next pages in sequence and caches their tokens until the requested page
// results are returned.
while (currentPageNumber <= pageNumber)
{
// Fetches the next page.
Console.WriteLine($"Fetching page #{currentPageNumber}...");
request.PageToken = pageTokens[currentPageNumber - 1];
response = googleAdsService.Search(request)
.AsRawResponses().First();
CacheNextPageToken(pageTokens, response, currentPageNumber);
currentPageNumber++;
}
// Prints the results of the requested page.
Console.WriteLine($"Printing results found for the page #{pageNumber}");
foreach (GoogleAdsRow row in response.Results)
{
Campaign c = row.Campaign;
Console.WriteLine($" - Campaign with ID {c.Id} and name '{c.Name}'");
}
}
PHP
/**
* Fetches and prints the results of a page of a search using a cache of page tokens.
*
* @param GoogleAdsServiceClient $googleAdsServiceClient the Google Ads API Service client
* @param int $customerId the customer ID
* @param string $searchQuery the search query
* @param array $searchOptions the search options
* @param int $pageNumber the number of the page to fetch and print results for
* @param array &$pageTokens the cache of page tokens to use and update
*/
private static function fetchAndPrintPageResults(
GoogleAdsServiceClient $googleAdsServiceClient,
int $customerId,
string $searchQuery,
array $searchOptions,
int $pageNumber,
array &$pageTokens
) {
// There is no need to fetch the pages we already know the page tokens for.
if (isset($pageTokens[$pageNumber])) {
printf(
'The token of the requested page was cached, we will use it to get the results.%s',
PHP_EOL
);
$currentPageNumber = $pageNumber;
} else {
printf(
'The token of the requested page was never cached, we will use the closest page ' .
'we know the token for (page #%d) and sequentially get pages from there.%s',
count($pageTokens),
PHP_EOL
);
$currentPageNumber = count($pageTokens);
}
// Fetches next pages in sequence and caches their tokens until the requested page results
// are returned.
while ($currentPageNumber <= $pageNumber) {
// Fetches the next page.
printf('Fetching page #%d...%s', $currentPageNumber, PHP_EOL);
$response = $googleAdsServiceClient->search(
$customerId,
$searchQuery,
$searchOptions + [
// Uses the page token cached for the current page number.
'pageToken' => $pageTokens[$currentPageNumber]
]
);
self::cacheNextPageToken($pageTokens, $response->getPage(), $currentPageNumber);
$currentPageNumber++;
}
// Prints the results of the requested page.
printf('Printing results found for the page #%d:%s', $pageNumber, PHP_EOL);
foreach ($response->getPage()->getIterator() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
printf(
" - Campaign with ID %d and name '%s'.%s",
$googleAdsRow->getCampaign()->getId(),
$googleAdsRow->getCampaign()->getName(),
PHP_EOL
);
}
}
Python
def fetch_and_print_results(
client, customer_id, query, page_number, page_tokens
):
"""Fetches and prints the results of a page using a cache of page tokens.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
query: the search query.
page_number: the number of the page to fetch and print results for.
page_tokens: the cache of page tokens to use and update.
"""
current_page_number = None
# There is no need to fetch the pages we already know the page tokens for.
if page_tokens.get(page_number, None):
print(
"The token of the request page was cached, we will use it to get "
"the results."
)
current_page_number = page_number
else:
count = len(page_tokens.keys())
print(
"The token of the requested page was never cached, we will use "
f"the closest page we know the token for (page {count}) and "
"sequentially get pages from there."
)
current_page_number = count
googleads_service = client.get_service("GoogleAdsService")
# Fetches next pages in sequence and caches their tokens until the requested
# page results are returned.
while current_page_number <= page_number:
# Fetches the next page.
print(f"Fetching page {current_page_number}...")
request = client.get_type("SearchGoogleAdsRequest")
request.customer_id = customer_id
request.query = query
request.page_size = _PAGE_SIZE
request.return_total_results_count = True
# Uses the page token cached for the current page number.
request.page_token = page_tokens[current_page_number]
response = googleads_service.search(request=request)
cache_next_page_token(page_tokens, response, current_page_number)
current_page_number += 1
# Prints the results of the requested page.
print(f"Printing results found for the page {page_number}.")
for row in response.results:
print(
f" - Campaign with ID {row.campaign.id} and name "
f"{row.campaign.name}."
)
Ruby
def fetch_and_print_page_results(client, customer_id, query, page_size,
return_total_results_count, page_number, page_tokens)
if page_tokens.has_key?(page_number)
puts 'The page token for the request page was cached. Reusing it.'
current_page = page_number
else
puts "The token for the requested page has not been cached yet. We will start " \
"at page #{page_tokens.size} and request and cache pages until we find it."
current_page = page_tokens.size
end
while current_page <= page_number
puts page_tokens
response = client.service.google_ads.search(
customer_id: customer_id,
query: query,
page_size: page_size,
return_total_results_count: return_total_results_count,
page_token: page_tokens[current_page],
)
cache_next_page_token(page_tokens, response.page, current_page + 1)
current_page += 1
end
puts "Printing results found for page #{page_number}."
response.page.response.results.each do |result|
puts "- Campaign with ID #{result.campaign.id} and name #{result.campaign.name}."
end
end
Perl
# Fetches and prints the results of a page of a search using a cache of page tokens.
sub fetch_and_print_page_results {
my (
$api_client, $customer_id, $query,
$search_options, $page_number, $page_tokens
) = @_;
my $current_page_number = undef;
# There is no need to fetch the pages we already know the page tokens for.
if (exists $page_tokens->{$page_number}) {
print "The token of the requested page was cached, " .
"we will use it to get the results.\n";
$current_page_number = $page_number;
} else {
printf "The token of the requested page was never cached, " .
"we will use the closest page we know the token for (page #%d) " .
"and sequentially get pages from there.\n", scalar keys %$page_tokens;
$current_page_number = scalar keys %$page_tokens;
}
# Fetch next pages in sequence and cache their tokens until the requested page
# results are returned.
my $response = undef;
while ($current_page_number <= $page_number) {
# Fetch the next page.
printf "Fetching page #%d...\n", $current_page_number;
$response = $api_client->GoogleAdsService()->search({
customerId => $customer_id,
query => $query,
%$search_options,
# Use the page token cached for the current page number.
pageToken => $page_tokens->{$current_page_number}});
cache_next_page_token($page_tokens, $response, $current_page_number);
$current_page_number++;
}
# Print the results of the requested page.
printf "Printing results found for the page #%d:\n", $page_number;
foreach my $google_ads_row (@{$response->{results}}) {
printf
" - Campaign with ID %d and name '%s'.\n",
$google_ads_row->{campaign}{id},
$google_ads_row->{campaign}{name};
}
}