클라이언트 라이브러리

Google의 클라이언트 라이브러리는 높은 수준의 보기와 Google Ads API 기능의 기본 빌딩 블록을 제공하여 앱을 더 쉽게 개발할 수 있게 해줍니다. API를 처음 사용하는 경우 한 가지 방법으로 시작하는 것이 좋습니다.

클라이언트 라이브러리 소스 분포 코드 예
자바 google-ads-java Maven, tar.gz GitHub에서 보기
.NET google-ads-dotnet tar.gz, 우편번호 GitHub에서 보기
PHP google-ads-php를 참조하세요. tar.gz GitHub에서 보기
Python google-ads-python tar.gz, 우편번호 GitHub에서 보기
Ruby google-ads-ruby gem, tar.gz, zip GitHub에서 보기
Perl google-ads-perl tar.gz, 우편번호 GitHub에서 보기

지원되는 API 버전

아래 표에는 사용 가능한 각 API 버전을 지원하는 특정 라이브러리 버전이 나와 있습니다.

API 버전 Python 라이브러리 버전 Ruby 라이브러리 버전 PHP 라이브러리 버전 자바 라이브러리 버전 .NET 라이브러리 버전 Perl 라이브러리 버전
v11 17.0.0 18.0.0 15.1.0 19.0.0 12.1.0 12.0.0
v10 15.0.0 16.0.0 14.0.0 17.0.0 11.0.0 10.0.0
v9 14.1.0 15.0.0 12.1.0 16.0.0 10.2.0 9.2.0

구성

각 Ads API 클라이언트 라이브러리는 동작을 맞춤설정하는 데 사용할 수 있는 다양한 구성 설정과 로드 방법을 제공합니다.

다음은 모든 클라이언트 라이브러리에 공통되고 환경 설정을 설정하기 위해 로드할 수 있는 환경 변수입니다.

  • 클라이언트 라이브러리
    • GOOGLE_ADS_CONFIGURATION_FILE_PATH: 구성 파일의 경로.
  • OAuth2
    • 애플리케이션 모드
      • GOOGLE_ADS_CLIENT_ID : 이 값을 OAuth2 클라이언트 ID로 설정합니다.
      • GOOGLE_ADS_CLIENT_SECRET : 이 값을 OAuth2 클라이언트 보안 비밀로 설정합니다.
      • GOOGLE_ADS_REFRESH_TOKEN: OAuth2 토큰을 재사용하려면 이 값을 사전 생성된 OAuth2 갱신 토큰으로 설정합니다. 이 설정은 선택사항입니다.
    • 서비스 계정 모드
      • GOOGLE_ADS_JSON_KEY_FILE_PATH : 이 값을 OAuth2 JSON 구성 파일 경로로 설정합니다.
      • GOOGLE_ADS_IMPERSONATED_EMAIL: 이 값을 가장하고 있는 계정의 이메일 주소로 설정합니다.
  • Google Ads API
    • GOOGLE_ADS_DEVELOPER_TOKEN: 개발자 토큰으로 설정합니다.
    • GOOGLE_ADS_LOGIN_CUSTOMER_ID : 하이픈 (-) 없이 요청에서 사용하도록 승인된 고객의 고객 ID입니다.
    • GOOGLE_ADS_LINKED_CUSTOMER_ID: 이 헤더는 Google Ads UI에서 연결된 계정을 통해 권한이 부여되었을 때(Google Ads API의 AccountLink 리소스에서) 항목의 리소스를 업데이트하는 메서드에만 필요합니다. 이 값을 지정된 고객 ID의 리소스를 업데이트하는 데이터 제공업체의 고객 ID로 설정합니다. 하이픈(-) 없이 설정해야 합니다. 연결된 계정에 대한 자세한 내용은 고객센터를 참조하세요.

환경 변수는 일반적으로 bash 구성 파일(예: $HOME 디렉터리에 있는 .bashrc 또는 .bash_profile 파일)에 정의됩니다. 명령줄을 사용하여 정의할 수도 있습니다.

터미널을 사용하여 .bashrc 파일을 사용하여 환경 변수를 정의하는 몇 가지 기본 단계는 다음과 같습니다.

# Append the line "export GOOGLE_ADS_CLIENT_ID=1234567890" to
# the bottom of your .bashrc file.
echo "export GOOGLE_ADS_CLIENT_ID=1234567890" >> ~/.bashrc

# Update your bash environment to use the most recently updated
# version of your .bashrc file.
src ~/.bashrc

터미널 인스턴스에 다음과 같이 명령줄에서 직접 환경 변수를 설정할 수도 있습니다.

export GOOGLE_ADS_CLIENT_ID=1234567890

또 다른 방법은 환경 변수를 사용하는 명령어를 호출할 때 환경 변수를 설정하는 것입니다.

GOOGLE_ADS_CLIENT_ID=1234567890 php /path/to/script/that/uses/envvar.php

진단 도구

Google Ads 의사는 클라이언트 라이브러리 환경을 분석하여

  • Google Ads API를 사용하여 OAuth2 사용자 인증 정보를 확인합니다.
  • 구성 파일의 OAuth2 문제를 해결하는 방법을 안내합니다.

다음 단계를 따라 즉시 문제를 진단하기 위한 명령줄 도구를 다운로드하세요.

Linux (64비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/linux/amd64
    ./oauthdoctor -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

Windows (64비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/windows/amd64
    ./oauthdoctor.exe -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

Mac OS X (64비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/darwin/amd64
    ./oauthdoctor -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

Linux (32비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/linux/386
    ./oauthdoctor -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

Windows (32비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/windows/386
    ./oauthdoctor.exe -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

Mac OS X (32비트)

    git clone https://github.com/googleads/google-ads-doctor.git
    cd google-ads-doctor/oauthdoctor/bin/darwin/386
    ./oauthdoctor -language [java|dotnet|php|python|ruby] \
      -oauthtype [web|installed_app|service_account] \
      -configpath [/my/config/file/path] \
      -verbose

도구와 함께 추가 옵션을 가져오려면 README를 읽거나 다음 명령어를 실행합니다.

Linux / Mac OS X

    ./oauthdoctor -help

Windows

    ./oauthdoctor.exe -help

검색 페이지 나누기

GoogleAdsService.Search는 일반적으로 결과 페이지를 표시하는 대화형 앱에 사용됩니다.

클라이언트 라이브러리는 결과를 반복할 때 한 번에 모두 순차적으로 다운로드하고 처리할 수 있도록 페이징을 자동으로 구현합니다.

자바

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long labelId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(
                "SELECT campaign.id, campaign.name, label.id, label.name "
                    + "FROM campaign_label WHERE label.id = "
                    + labelId
                    + " ORDER BY campaign.id")
            .build();
    // Issues the search request.
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
    // Checks if the total results count is greater than 0.
    if (searchPagedResponse.getPage().getResponse().getTotalResultsCount() > 0) {
      // Iterates over all rows in all pages and prints the requested field values for the
      // campaigns and labels in each row. The results include the campaign and label
      // objects because these were included in the search criteria.
      for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
        System.out.printf(
            "Campaign found with name '%s', ID %d, and label: %s.%n",
            googleAdsRow.getCampaign().getName(),
            googleAdsRow.getCampaign().getId(),
            googleAdsRow.getLabel().getName());
      }
    } else {
      System.out.println("No campaigns were found.");
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long labelId)
{
    // Get the GoogleAdsServiceClient.
    GoogleAdsServiceClient googleAdsService =
        client.GetService(Services.V11.GoogleAdsService);

    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
    {
        CustomerId = customerId.ToString(),
        Query = "SELECT campaign.id, campaign.name, label.id, label.name " +
            $"FROM campaign_label WHERE label.id = {labelId} ORDER BY campaign.id",
    };

    try
    {
        int count = 0;
        // Issues the search request and prints the result.
        foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request))
        {
            count++;
            Console.WriteLine($"Campaign found with name '{googleAdsRow.Campaign.Name}'" +
                $", ID {googleAdsRow.Campaign.Id}, and label: " +
                $"'${googleAdsRow.Label.Name}'.");
        }
        if (count == 0)
        {
            Console.WriteLine("No campaigns were found.");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $labelId
) {
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that will retrieve all campaign labels with the specified
    // label ID.
    $query = "SELECT campaign.id, campaign.name, label.id, label.name " .
        "FROM campaign_label WHERE label.id = $labelId ORDER BY campaign.id";
    // Issues a search request by specifying page size.
    $response =
        $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

    // Iterates over all rows in all pages and prints the requested field values for the
    // campaigns and labels in each row. The results include the campaign and label
    // objects because these were included in the search criteria.
    foreach ($response->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign found with name '%s', ID %d, and label: '%s'.%s",
            $googleAdsRow->getCampaign()->getName(),
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getLabel()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id, label_id, page_size):
    """Demonstrates how to retrieve all campaigns by a given label ID.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: A label ID to use when searching for campaigns.
        page_size: An int of the number of results to include in each page of
            results.
    """
    ga_service = client.get_service("GoogleAdsService")

    # Creates a query that will retrieve all campaign labels with the
    # specified label ID.
    query = f"""
        SELECT
            campaign.id,
            campaign.name,
            label.id,
            label.name
         FROM campaign_label
         WHERE label.id = "{label_id}"
         ORDER BY campaign.id"""

    # Retrieves a google.api_core.page_iterator.GRPCIterator instance
    # initialized with the specified request parameters.
    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = query
    request.page_size = page_size

    iterator = ga_service.search(request=request)

    # Iterates over all rows in all pages and prints the requested field
    # values for the campaigns and labels in each row. The results include
    # the campaign and label objects because these were included in the
    # search criteria.
    for row in iterator:
        print(
            f'Campaign found with ID "{row.campaign.id}", name '
            f'"{row.campaign.name}", and label "{row.label.name}".'
        )


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="Lists all campaigns for specified customer."
    )
    # 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.",
    )
    parser.add_argument(
        "-l",
        "--label_id",
        type=str,
        required=True,
        help="A label ID associated with a campaign.",
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.label_id,
            _DEFAULT_PAGE_SIZE,
        )
    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'\tError 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

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

  query = <<~EOQUERY
    SELECT campaign.id, campaign.name, label.id, label.name
    FROM campaign_label WHERE label.id = '#{label_id}' ORDER BY campaign.id
  EOQUERY

  ga_service = client.service.google_ads
  response = ga_service.search(
    customer_id: customer_id,
    query: query,
    page_size: PAGE_SIZE,
  )

  response.each do |row|
    puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
  end
end
      

Perl

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

  # Create the search query.
  my $search_query =
    "SELECT campaign.id, campaign.name, label.id, label.name " .
    "FROM campaign_label WHERE label.id = $label_id ORDER BY campaign.id";

  # Create a search Google Ads request that will retrieve all campaign labels
  # with the specified label Id using pages of the specified page size.
  my $search_request =
    Google::Ads::GoogleAds::V11::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query,
      pageSize   => PAGE_SIZE
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  # Iterate over all rows in all pages and print the requested field values for the
  # campaigns and labels in each row. The results include the campaign and label
  # objects because these were included in the search criteria.
  while ($iterator->has_next) {
    my $google_ads_row = $iterator->next;

    printf "Campaign found with name '%s', ID %d, and label: '%s'.\n",
      $google_ads_row->{campaign}{name}, $google_ads_row->{campaign}{id},
      $google_ads_row->{label}{name};
  }

  return 1;
}
      

사용 사례에 따라 다음을 실행해야 할 수도 있습니다.

  • 가져오는 페이지 수를 최적화합니다.
  • 한 번에 저장되는 결과의 양을 최적화합니다.
  • 특정 순서로 검색결과 페이지를 다운로드하고 처리합니다.

이렇게 하려면 결과 대신 페이지 토큰을 저장하면 코드가 더 복잡해집니다.

자바

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

코드 예

Google Ads API의 몇 가지 일반적인 함수의 코드 예를 확인하세요.