Navigate Search Result Pages Caching Tokens

Stay organized with collections Save and categorize content based on your preferences.

Java

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.misc;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.services.GoogleAdsRow;
import com.google.ads.googleads.v11.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v11.services.GoogleAdsServiceClient.SearchPage;
import com.google.ads.googleads.v11.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v11.services.SearchGoogleAdsRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * GoogleAdsService.search results are paginated, but they can only be retrieved in sequence
 * starting by the first page. More details at
 * https://developers.google.com/google-ads/api/docs/reporting/paging.
 *
 * <p>This example searches campaigns illustrating how GoogleAdsService.search result page tokens
 * can be cached and reused to retrieve previous pages. This is useful when you need to request
 * pages that were already requested in the past without starting over from the first page. For
 * example, it can be used to implement an interactive application that displays a page of results
 * at a time without caching all the results first.
 *
 * <p>To add campaigns, run {@link com.google.ads.googleads.examples.basicoperations.AddCampaigns}.
 */
public class NavigateSearchResultPagesCachingTokens {

  // The maximum number of results to retrieve.
  private static final int RESULTS_LIMIT = 10;
  // The size of the paginated search result pages.
  private static final int PAGE_SIZE = 3;

  private static class NavigateSearchResultPagesCachingTokensParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;
  }

  public static void main(String args[]) {
    NavigateSearchResultPagesCachingTokensParams params =
        new NavigateSearchResultPagesCachingTokensParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("ENTER_CUSTOMER_ID_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new NavigateSearchResultPagesCachingTokens().runExample(googleAdsClient, params.customerId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs this example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private static void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    // The cache of page tokens. It is stored in-memory and in ascendant order of page number.
    // The first page's token is always an empty string.
    SortedMap<Integer, String> pageTokens = new TreeMap<>();
    pageTokens.put(1, "");

    // Creates a query that retrieves the campaigns.
    String query =
        String.format(
            "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.name LIMIT %d",
            RESULTS_LIMIT);

    // Creates a paginated search request.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(query)
            .setReturnTotalResultsCount(true)
            .build();

    int totalNumberOfPages;
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      System.out.println("--- 0. Fetching page 1 to get metadata:");
      // Issues a paginated search request.
      SearchPagedResponse response = googleAdsServiceClient.search(request);
      cacheNextPageToken(pageTokens, response.getPage(), 2);

      // Determines the total number of results and prints it.
      // The total results count does not take into consideration the LIMIT clause of the query,
      // so we need to find the minimal value between the limit and the total results count.
      long totalNumberOfResults =
          Math.min(RESULTS_LIMIT, response.getPage().getResponse().getTotalResultsCount());
      System.out.printf("Total number of campaigns found: %d.%n", totalNumberOfResults);

      // Determines the total number of pages and prints it.
      totalNumberOfPages = (int) Math.ceil(totalNumberOfResults / (double) PAGE_SIZE);
      System.out.printf("Total number of pages: %d.%n", totalNumberOfPages);
      if (totalNumberOfPages == 0) {
        System.out.println("Could not find any campaigns.");
        return;
      }
    }

    // Demonstrates how the logic works when iterating pages forward. We select a page that is
    // in the middle of the result set so that only a subset of the page tokens will be cached.
    int middlePageNumber = (int) Math.ceil(totalNumberOfPages / 2.0);
    System.out.printf("--- 1. Printing results of the middle page (page %d):%n", middlePageNumber);
    fetchAndPrintPageResults(googleAdsClient, customerId, query, middlePageNumber, pageTokens);

    // Demonstrates how the logic works when iterating pages backward with some page tokens that
    // are not already cached.
    System.out.println("--- 2. Printing results of the last page to the first:");
    for (int pageNumber = totalNumberOfPages; pageNumber > 0; pageNumber--) {
      System.out.printf("-- Page %d results:%n", pageNumber);
      fetchAndPrintPageResults(googleAdsClient, customerId, query, pageNumber, pageTokens);
    }
  }

  /**
   * 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++;
      }
    }
  }

  /**
   * Updates the cache of page tokens based on a page that was retrieved.
   *
   * @param pageTokens the cache of page tokens to update.
   * @param page the page that was retrieved.
   * @param pageNumber the number of the page the cached token will retrieve.
   */
  private static void cacheNextPageToken(
      SortedMap<Integer, String> pageTokens, SearchPage page, int pageNumber) {
    if (page.hasNextPage() && !pageTokens.containsKey(pageNumber)) {
      // Updates the cache with the next page token if it is not set yet.
      pageTokens.put(pageNumber, page.getNextPageToken());
      System.out.printf("Cached token for page %d.%n", pageNumber);
    }
  }
}

      

C#

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// GoogleAdsService.Search results are paginated but they can only be retrieved in sequence
    /// starting by the first page. More details at
    /// https://developers.google.com/google-ads/api/docs/reporting/paging.
    ///
    /// This code example searches campaigns illustrating how GoogleAdsService.Search result page
    /// tokens can be cached and reused to retrieve previous pages. This is useful when you need
    /// to request pages that were already requested in the past without starting over from the
    /// first page. For example, it can be used to implement an interactive application that
    /// displays a page of results at a time without caching all the results first.
    /// </summary>
    public class NavigateSearchResultPagesCachingTokens : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="NavigateSearchResultPagesCachingTokens"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }
        }

        /// <summary>
        /// The maximum number of results to retrieve.
        /// </summary>
        private const long RESULTS_LIMIT = 11;

        /// <summary>
        /// The size of the paginated search result pages.
        /// </summary>
        private const int PAGE_SIZE = 3;

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            NavigateSearchResultPagesCachingTokens codeExample =
                new NavigateSearchResultPagesCachingTokens();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description => "GoogleAdsService.Search results are paginated but " +
            "they can only be retrieved in sequence starting by the first page. More details " +
            "at https://developers.google.com/google-ads/api/docs/reporting/paging. This code " +
            "example searches campaigns illustrating how GoogleAdsService.Search result page " +
            "tokens can be cached and reused to retrieve previous pages. This is useful when " +
            "you need to request pages that were already requested in the past without starting " +
            "over from the first page. For example, it can be used to implement an interactive " +
            "application that displays a page of results at a time without caching all the " +
            "results first.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V11.GoogleAdsService);

            // The cache of page tokens. The first page's token is always an empty string.
            Dictionary<int, string> pageTokens = new Dictionary<int, string>();
            CacheNextPageToken(pageTokens, null, 0);

            Console.WriteLine("---0. Fetch page #1 to get metadata");

            // Creates a query that retrieves the campaigns.
            string query = $"SELECT campaign.id, campaign.name FROM campaign ORDER BY " +
                $"campaign.name LIMIT {RESULTS_LIMIT}";

            // Issues a paginated search request.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                Query = query,
                CustomerId = customerId.ToString(),
                // Sets the number of results to return per page.
                PageSize = PAGE_SIZE,
                // Requests to return the total results count. This is necessary to determine
                // how many pages of results there are.
                ReturnTotalResultsCount = true
            };

            try
            {
                SearchGoogleAdsResponse response = googleAdsService.Search(request)
                    .AsRawResponses().First();
                CacheNextPageToken(pageTokens, response, 1);

                // Determines the total number of results and prints it.
                // The total results count does not take into consideration the LIMIT clause of
                // the query so we need to find the minimal value between the limit and the total
                // results count.
                long totalNumberOfResults = Math.Min(RESULTS_LIMIT, response.TotalResultsCount);
                Console.WriteLine($"Total number of campaigns found: {totalNumberOfResults}.");

                // Determines the total number of pages and prints it.
                int totalNumberOfPages =
                    (int)Math.Ceiling((double)totalNumberOfResults / PAGE_SIZE);
                Console.WriteLine($"Total number of pages: {totalNumberOfPages}.");
                if (totalNumberOfResults == 0)
                {
                    Console.WriteLine("Could not find any campaigns.");
                    return;
                }

                // Demonstrates how the logic works when iterating pages forward. We select a
                // page that is in the middle of the result set so that only a subset of the page
                // tokens will be cached.
                int middlePageNumber = (int)Math.Ceiling((double)totalNumberOfPages / 2);
                Console.WriteLine($"--- 1. Print results of the page #{middlePageNumber}");
                FetchAndPrintPageResults(googleAdsService, request, middlePageNumber, pageTokens);

                // Demonstrates how the logic works when iterating pages backward with some page
                // tokens that are not already cached.
                Console.WriteLine("--- 2. Print results from the last page to the first");
                for (int i = totalNumberOfPages; i > 0; i--)
                {
                    Console.WriteLine($"--- Printing results for page #{i}");
                    FetchAndPrintPageResults(googleAdsService, request, i, pageTokens);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <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}'");
            }
        }


        /// <summary>
        /// Updates the cache of page tokens based on a page that was retrieved.
        /// </summary>
        /// <param name="pageTokens">The cache of page tokens to update.</param>
        /// <param name="response">The response that was retrieved.</param>
        /// <param name="pageNumber">The number of the page that was retrieved.</param>
        /// <returns></returns>
        private static void CacheNextPageToken(Dictionary<int, string> pageTokens,
            SearchGoogleAdsResponse response, int pageNumber)
        {
            if (pageNumber == 0)
            {
                pageTokens[0] = "";
                return;
            }
            if (string.IsNullOrEmpty(response.NextPageToken) || pageTokens.ContainsKey(pageNumber))
            {
                return;
            }
            // Updates the cache with the next page token if it is not set yet.
            pageTokens[pageNumber] = response.NextPageToken;
            Console.WriteLine($"Cached token for page #{pageNumber + 1}.");
        }
    }
}
      

PHP

<?php

/**
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\Misc;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V11\Services\GoogleAdsServiceClient;
use Google\ApiCore\ApiException;
use Google\ApiCore\Page;

/**
 * GoogleAdsService.Search results are paginated but they can only be retrieved in sequence
 * starting by the first page. More details at
 * https://developers.google.com/google-ads/api/docs/reporting/paging.
 *
 * This example searches campaigns illustrating how GoogleAdsService.Search result page tokens can
 * be cached and reused to retrieve previous pages. This is useful when you need to request pages
 * that were already requested in the past without starting over from the first page. For example,
 * it can be used to implement an interactive application that displays a page of results at a time
 * without caching all the results first.
 *
 * To add campaigns, run AddCampaigns.php.
 * For an example in a webapp context, see the code example LaravelSampleApp.
 */
class NavigateSearchResultPagesCachingTokens
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    // The maximum number of results to retrieve.
    private const RESULTS_LIMIT = 10;
    // The size of the paginated search result pages.
    private const PAGE_SIZE = 3;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // The cache of page tokens which is stored in-memory with the page numbers as keys.
        // The first page's token is always an empty string.
        $pageTokens = [1 => ''];

        printf('%s--- 0. Fetch page #1 to get metadata:%1$s%1$s', PHP_EOL);

        // Creates a query that retrieves the campaigns.
        $query = sprintf(
            'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.name LIMIT %d',
            self::RESULTS_LIMIT
        );

        // Issues a paginated search request.
        $searchOptions = [
            // Sets the number of results to return per page.
            'pageSize' => self::PAGE_SIZE,
            // Requests to return the total results count. This is necessary to determine how many
            // pages of results there are.
            'returnTotalResultsCount' => true
        ];
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        $response = $googleAdsServiceClient->search($customerId, $query, $searchOptions);
        self::cacheNextPageToken($pageTokens, $response->getPage(), 1);

        // Determines the total number of results and prints it.
        // The total results count does not take into consideration the LIMIT clause of the query
        // so we need to find the minimal value between the limit and the total results count.
        $totalNumberOfResults = min(
            self::RESULTS_LIMIT,
            $response->getPage()->getResponseObject()->getTotalResultsCount()
        );
        printf('Total number of campaigns found: %d.%s', $totalNumberOfResults, PHP_EOL);

        // Determines the total number of pages and prints it.
        $totalNumberOfPages = ceil($totalNumberOfResults / self::PAGE_SIZE);
        printf('Total number of pages: %d.%s', $totalNumberOfPages, PHP_EOL);
        if (!$totalNumberOfPages) {
            print 'Could not find any campaigns.' . PHP_EOL;
            exit(1);
        }

        // Demonstrates how the logic works when iterating pages forward. We select a page that is
        // in the middle of the result set so that only a subset of the page tokens will be cached.
        $middlePageNumber = ceil($totalNumberOfPages / 2);
        printf('%s--- 1. Print results of the page #%d:%1$s%1$s', PHP_EOL, $middlePageNumber);
        self::fetchAndPrintPageResults(
            $googleAdsServiceClient,
            $customerId,
            $query,
            $searchOptions,
            $middlePageNumber,
            $pageTokens
        );

        // Demonstrates how the logic works when iterating pages backward with some page tokens that
        // are not already cached.
        printf('%s--- 2. Print results from the last page to the first:%1$s', PHP_EOL);
        foreach (range($totalNumberOfPages, 1) as $pageNumber) {
            printf('%s-- Printing results for page #%d:%1$s', PHP_EOL, $pageNumber);
            self::fetchAndPrintPageResults(
                $googleAdsServiceClient,
                $customerId,
                $query,
                $searchOptions,
                $pageNumber,
                $pageTokens
            );
        }
    }

    /**
     * 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
            );
        }
    }

    /**
     * Updates the cache of page tokens based on a page that was retrieved.
     *
     * @param array &$pageTokens the cache of page tokens to update
     * @param Page $page the page that was retrieved
     * @param int $pageNumber the number of the page that was retrieved
     */
    private static function cacheNextPageToken(array &$pageTokens, Page $page, int $pageNumber)
    {
        if ($page->getNextPageToken() && !isset($pageTokens[$pageNumber + 1])) {
            // Updates the cache with the next page token if it is not set yet.
            $pageTokens[$pageNumber + 1] = $page->getNextPageToken();
            // Prints in green color for better console readability.
            printf("\e[0;32mCached token for page #%d.\e[0m%s", $pageNumber + 1, PHP_EOL);
        }
    }
}

NavigateSearchResultPagesCachingTokens::main();

      

Python

#!/usr/bin/env python
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to cache page tokens in paged search requests.

GoogleAdsService.Search results are paginated but they can only be retrieved in
sequence starting with the first page. More details at:
https://developers.google.com/google-ads/api/docs/reporting/paging.

This example searches campaigns illustrating how GoogleAdsService.Search result
page tokens can be cached and reused to retrieve previous pages. This is useful
when you need to request pages that were already requested in the past without
starting over from the first page. For example, it can be used to implement an
interactive application that displays a page of results at a time without
caching all the results first.

To add campaigns, run the basic_examples/add_campaigns.py example.
"""


import argparse
import math
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


# The maximum number of results to retrieve in the query.
_RESULTS_LIMIT = 10
# The number of results to return per page.
_PAGE_SIZE = 3


def main(client, customer_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    # The cache of page tokens which is stored in-memory with the page numbers
    # as keys. The first page's token is always an empty string.
    page_tokens = {1: ""}

    print("\n--- 0. Fetch page #1 to get metadata:\n")

    # Creates a query that retrieves the campaigns.
    query = f"""
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.name
        LIMIT {_RESULTS_LIMIT}"""

    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = query
    # Sets the number of results to return per page.
    request.page_size = _PAGE_SIZE
    # Requests to return the total results count. This is necessary to determine
    # how many pages of results there are.
    request.return_total_results_count = True

    googleads_service = client.get_service("GoogleAdsService")
    response = googleads_service.search(request=request)
    cache_next_page_token(page_tokens, response, 1)

    # Determines the total number of results and prints it. The total results
    # count does not take into consideration the LIMIT clause of the query so
    # we need to find the minimal value between the limit and the total results
    # count.
    total_number_of_results = min(_RESULTS_LIMIT, response.total_results_count)
    print(f"Total number of campaigns found: {total_number_of_results}.")

    # Determines the total number of pages and prints it.
    total_number_of_pages = math.ceil(total_number_of_results / _PAGE_SIZE)
    print(f"Total number of pages: {total_number_of_pages}.")
    if not total_number_of_pages:
        print("Could not find any campaigns.")
        sys.exit(1)

    # Demonstrates how the logic works when iterating pages forward. We select
    # a page that is in the middle of the result set so that only a subset of
    # the page tokens will be cached.
    middle_page_number = math.ceil(total_number_of_pages / 2)
    print(f"\n--- 1. Print results of the page {middle_page_number}\n")
    fetch_and_print_results(
        client, customer_id, query, middle_page_number, page_tokens
    )


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}."
        )


def cache_next_page_token(page_tokens, page, page_number):
    """Updates the cache of page tokens based on a page that was retrieved.

    Args:
        page_tokens: a cache of page tokens to update.
        page: the search results page that was retrieved.
        page_number: the number of the page that was retrieved.
    """
    # Check if the page_token exists and that it hasn't already been cached.
    if page.next_page_token and not page_tokens.get(page_number, None):
        page_tokens[page_number + 1] = page.next_page_token
        print(f"Cached token for page #{page_number + 1}.")


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v11")

    parser = argparse.ArgumentParser(
        description=(
            "Demonstrates how to cache and reuse page tokens in a "
            "GoogleAdService.Search request."
        )
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )

    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'Error with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# GoogleAdsService.Search results are paginated but they can only be retrieved
# in sequence starting by the first page. More details at
# https://developers.google.com/google-ads/api/docs/reporting/paging.
#
# This example searches campaigns illustrating how GoogleAdsService.Search
# result page tokens can be cached and reused to retrieve previous pages. This
# is useful when you need to request pages that were already requested in the
# past without starting over from the first page. For example, it can be used
# to implement an interactive application that displays a page of results at a
# time without caching all the results first.
#
# To add campaigns, run add_campaigns.rb.

require 'optparse'
require 'google/ads/google_ads'

def navigate_search_result_pages_caching_tokens(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # The cache of page tokens. The key is the page number.
  # The first page's token is always the empty string.
  page_tokens = {
    1 => ''
  }

  puts "Fetching page 1 to get metadata"
  query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.name LIMIT #{RESULTS_LIMIT}"
  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
    page_size: PAGE_SIZE,
    return_total_results_count: true,
  )

  cache_next_page_token(page_tokens, response.page, 2)

  # The total results count does not take into consideration the LIMIT clause
  # of the query so we need to find the minimal value between the limit and the
  # total results count.
  total_results = [
    RESULTS_LIMIT,
    response.page.response.total_results_count,
  ].min
  puts "Found ${total_results} campaigns."

  total_pages = (total_results.to_f / PAGE_SIZE).ceil
  raise "Could not find any campaigns." if total_pages == 0

  middle_page = (total_pages / 2.0).ceil
  puts "Printing results from page #{middle_page}."
  fetch_and_print_page_results(
    client,
    customer_id,
    query,
    PAGE_SIZE,
    true,
    middle_page,
    page_tokens,
  )

  puts 'Print all pages, starting at the last page and moving to the first.'
  (1..total_pages).reverse_each do |page_number|
    fetch_and_print_page_results(
      client,
      customer_id,
      query,
      PAGE_SIZE,
      true,
      page_number,
      page_tokens,
    )
  end
end

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

def cache_next_page_token(page_tokens, page, page_number)
  if !page.next_page_token.nil? && page_tokens[page_number].nil?
    page_tokens[page_number] = page.next_page_token
    puts "Caching token for page #{page_number}."
  end
end

if __FILE__ == $0
  # These limits are set low for demonstrative purposes.
  RESULTS_LIMIT = 10
  PAGE_SIZE = 3

  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    navigate_search_result_pages_caching_tokens(options.fetch(:customer_id).tr('-', ''))
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf('Error with message: %s\n', error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf('\tOn field: %s\n', field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf('\tType: %s\n\tCode: %s\n', k, v)
      end
    end
    raise
  end
end


      

Perl

#!/usr/bin/perl -w
#
# Copyright 2022, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# GoogleAdsService.Search results are paginated but they can only be retrieved in
# sequence starting by the first page. More details at
# https://developers.google.com/google-ads/api/docs/reporting/paging.
#
# This example searches campaigns illustrating how GoogleAdsService.Search result
# page tokens can be cached and reused to retrieve previous pages. This is useful
# when you need to request pages that were already requested in the past without
# starting over from the first page. For example, it can be used to implement an
# interactive application that displays a page of results at a time without caching
# all the results first.
#
# To add campaigns, run add_campaigns.pl.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use
  Google::Ads::GoogleAds::V11::Services::GoogleAdsService::SearchGoogleAdsRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use List::Util qw(min);
use POSIX qw(ceil);

# The maximum number of results to retrieve.
use constant RESULTS_LIMIT => 10;
# The size of the paginated search result pages.
use constant PAGE_SIZE => 3;

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";

sub navigate_search_result_pages_caching_tokens {
  my ($api_client, $customer_id) = @_;

  # The cache of page tokens which is stored in-memory with the page numbers as
  # keys. The first page's token is always an empty string.
  my $page_tokens = {1 => ""};

  printf "\n--- 0. Fetch page #1 to get metadata:\n\n";

  # Create a query that retrieves the campaigns.
  my $query =
    sprintf "SELECT campaign.id, campaign.name FROM campaign " .
    "ORDER BY campaign.name LIMIT %d",
    RESULTS_LIMIT;

  # Issue a paginated search request.
  my $search_options = {
    # Set the number of results to return per page.
    pageSize => PAGE_SIZE,
    # Request to return the total results count. This is necessary to determine
    # how many pages of results there are.
    returnTotalResultsCount => "true"
  };
  my $response = $api_client->GoogleAdsService()->search({
    customerId => $customer_id,
    query      => $query,
    %$search_options
  });
  cache_next_page_token($page_tokens, $response, 1);

  # Determine the total number of results and print it.
  # The total results count does not take into consideration the LIMIT clause of
  # the query, so we need to find the minimal value between the limit and the total
  # results count.
  my $total_number_of_results =
    min(RESULTS_LIMIT, $response->{totalResultsCount});
  printf "Total number of campaigns found: %d.\n", $total_number_of_results;

  # Determine the total number of pages and print it.
  my $total_number_of_pages = ceil($total_number_of_results / PAGE_SIZE);
  printf "Total number of pages: %d.\n", $total_number_of_pages;
  if ($total_number_of_pages == 0) {
    print "Could not find any campaigns.\n";
    exit 1;
  }

  # Demonstrate how the logic works when iterating pages forward. We select a page
  # that is in the middle of the result set so that only a subset of the page tokens
  # will be cached.
  my $middle_page_number = ceil($total_number_of_pages / 2);
  printf "\n--- 1. Print results of the page #%d:\n\n", $middle_page_number;
  fetch_and_print_page_results($api_client, $customer_id, $query,
    $search_options, $middle_page_number, $page_tokens);

  # Demonstrate how the logic works when iterating pages backward with some page
  # tokens that are not already cached.
  print "\n--- 2. Print results from the last page to the first:\n";
  foreach my $page_number (reverse 1 .. $total_number_of_pages) {
    printf "\n-- Printing results for page #%d:\n", $page_number;
    fetch_and_print_page_results(
      $api_client,     $customer_id, $query,
      $search_options, $page_number, $page_tokens
    );
  }

  return 1;
}

# 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};
  }
}

# Updates the cache of page tokens based on a page that was retrieved.
sub cache_next_page_token {
  my ($page_tokens, $response, $page_number) = @_;
  if (defined $response->{nextPageToken}
    && !exists $page_tokens->{$page_number + 1})
  {
    # Update the cache with the next page token if it is not set yet.
    $page_tokens->{$page_number + 1} = $response->{nextPageToken};
    printf "Cached token for page #%d.\n", $page_number + 1;
  }
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id);

# Call the example.
navigate_search_result_pages_caching_tokens($api_client,
  $customer_id =~ s/-//gr);

=pod

=head1 NAME

upload_image

=head1 DESCRIPTION

GoogleAdsService.Search results are paginated but they can only be retrieved in
sequence starting by the first page. More details at
https://developers.google.com/google-ads/api/docs/reporting/paging.

This example searches campaigns illustrating how GoogleAdsService.Search result
page tokens can be cached and reused to retrieve previous pages. This is useful
when you need to request pages that were already requested in the past without
starting over from the first page. For example, it can be used to implement an
interactive application that displays a page of results at a time without caching
all the results first.

To add campaigns, run add_campaigns.pl.

=head1 SYNOPSIS

navigate_search_result_pages_caching_tokens.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut