기본 사용법

이 가이드에서는 Google Ads API용 Perl 클라이언트 라이브러리 사용의 기본사항을 설명합니다.

클라이언트 초기화

라이브러리를 사용하려면 Google::Ads::GoogleAds::Client 인스턴스를 만드세요. 클라이언트는 구성 가이드에 자세히 설명된 대로 여러 방법으로 구성할 수 있습니다. 일반적인 접근 방식은 googleads.properties 파일을 사용하는 것입니다.

use strict;
use warnings;
use Google::Ads::GoogleAds::Client;

my $api_client = Google::Ads::GoogleAds::Client->new();

서비스 만들기

클라이언트가 초기화되면 다양한 API 서비스의 인스턴스를 만들 수 있습니다. 예를 들어 캠페인과 상호작용하려면 CampaignService 인스턴스를 만듭니다.

use strict;
use warnings;

my $campaign_service = $api_client->CampaignService();

기본적으로 $api_client는 설치된 라이브러리 출시의 DEFAULT_API_VERSION 서비스를 로드합니다 (최신 출시에서는 V25, v25.1와 같은 마이너 출시에서는 메이저 버전 모듈 V25 사용). 지원되는 특정 API 버전을 타겟팅하려면 version => "V25"를 Client->new({...})에 전달하거나 $api_client->set_version("V25")를 호출하세요.

API 호출

다음은 캠페인을 가져오기 위해 API를 호출하는 방법의 예입니다. 이 스니펫은 클라이언트를 초기화하고, 서비스를 만들고, 메서드를 호출하는 방법을 보여줍니다.

use strict;
use warnings;
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::V25::Services::GoogleAdsService::SearchGoogleAdsRequest;

# Initialize the Google Ads client. See the Configuration guide for options.
my $api_client = Google::Ads::GoogleAds::Client->new();

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

# Specify the customer ID and query.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $query = "SELECT campaign.name, campaign.status FROM campaign";

# Create a search request.
my $search_request =
  Google::Ads::GoogleAds::V25::Services::GoogleAdsService::SearchGoogleAdsRequest
  ->new({
    customerId => $customer_id,
    query      => $query,
  });

# Execute the search request.
my $search_response = $google_ads_service->search($search_request);

# Iterate over the results and print campaign names.
foreach my $google_ads_row (@{$search_response->{results} || []}) {
  printf "Campaign with resource name '%s' and name '%s'.\n",
    $google_ads_row->{campaign}->{resourceName},
    $google_ads_row->{campaign}->{name};
}

오류 처리

API 호출로 인해 오류가 발생할 수 있습니다. 기본적으로 die_on_faults는 0 (false)이며, 이로 인해 API 오류가 발생하면 서비스 메서드가 경고를 내보내고 Google::Ads::GoogleAds::GoogleAdsException 객체를 반환합니다. 반환된 응답이 GoogleAdsException인지 확인하고 get_google_ads_failure()를 호출하여 개별 GoogleAdsError 항목을 검사할 수 있습니다.

또는 Client->new({...})에서 die_on_faults => 1를 설정하거나 $api_client->set_die_on_faults(1)를 호출하는 경우 서비스 메서드는 API 오류가 발생할 때 원시 JSON 오류 응답으로 die()를 호출하며, 이는 eval 블록(if ($@))에서 포착할 수 있습니다.

use strict;
use warnings;
use Scalar::Util qw(blessed);
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::V25::Services::GoogleAdsService::SearchGoogleAdsRequest;

my $api_client = Google::Ads::GoogleAds::Client->new();
my $google_ads_service = $api_client->GoogleAdsService();
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $query = "SELECT campaign.name, campaign.status FROM campaign";
my $search_request =
  Google::Ads::GoogleAds::V25::Services::GoogleAdsService::SearchGoogleAdsRequest
  ->new({
    customerId => $customer_id,
    query      => $query,
  });

my $search_response = $google_ads_service->search($search_request);

if (blessed($search_response)
  && $search_response->isa("Google::Ads::GoogleAds::GoogleAdsException"))
{
  printf "An API exception occurred (HTTP %s, status '%s'): %s\n",
    $search_response->get_code(),
    $search_response->get_status(),
    $search_response->get_message();

  my $google_ads_failure = $search_response->get_google_ads_failure();
  if ($google_ads_failure) {
    foreach my $error (@{$google_ads_failure->{errors} || []}) {
      my ($error_type, $error_value) = %{$error->{errorCode} || {}};
      printf "  Error code (%s): %s\n",
        $error_type  || "unknown",
        $error_value || "UNKNOWN";
      printf "  Message: %s\n", $error->{message};
    }
  }
} else {
  foreach my $google_ads_row (@{$search_response->{results} || []}) {
    printf "Campaign name: %s\n", $google_ads_row->{campaign}->{name};
  }
}

다른 예시 살펴보기

examples 디렉터리에서 유용한 코드 샘플을 여러 개 확인할 수 있습니다. 대부분의 예에는 매개변수가 필요합니다. 매개변수를 인수로 전달하거나 (권장) 소스 코드에서 INSERT_XXXXX_HERE 값을 수정할 수 있습니다. 예의 사용법을 확인하려면 -help를 명령줄 인수로 전달하세요.

perl examples/basic_operations/get_campaigns.pl -help