클라이언트 라이브러리

Google의 클라이언트 라이브러리는 Google Cloud의 Google Ads API 기능을 통해 앱을 쉽고 빠르게 개발할 수 있습니다. 권장 조치 API를 처음 사용하는 경우 하나로 시작할 수 있습니다

클라이언트 라이브러리 소스 배포 코드 예시
자바 google-ads-java Maven, tar.gz GitHub에서 보기
.NET google-ads-dotnet nuget, tar.gz, zip GitHub에서 보기
PHP google-ads-php tar.gz GitHub에서 보기
Python google-ads-python tar.gz, zip GitHub에서 보기
Ruby google-ads-ruby gem, tar.gz, zip GitHub에서 보기
Perl google-ads-perl tar.gz, zip GitHub에서 보기

지원되는 API 버전

다음 표에는 어떤 클라이언트 라이브러리가 어떤 API 버전과 함께 작동하는지 표시됩니다.

자바

자바용 클라이언트 라이브러리
v17 Min: 32.0.0
Max:~
v16 Min: 30.0.0
Max:~
v15 Min: 28.0.0
Max:~

C#

.NET용 클라이언트 라이브러리
v17 Min: 20.1.0
Max:~
v16 Min: 18.1.0
Max:~
v15 Min: 17.1.0
Max:~

2,399필리핀

PHP용 클라이언트 라이브러리
v17 Min: 23.1.0
Max:~
v16 Min: 22.1.0
Max:~
v15 Min: 21.1.0
Max:~

Python

Python용 클라이언트 라이브러리
v17 Min: 24.1.0
Max:~
v16 Min: 23.1.0
Max:~
v15 Min: 22.1.0
Max:~

Ruby

Ruby용 클라이언트 라이브러리
v17 Min: 29.0.0
Max:~
v16 Min: 27.0.0
Max:~
v15 Min: 25.0.0
Max:~

Perl

Perl용 클라이언트 라이브러리
v17 Min: 23.0.0
Max:~
v16 Min: 21.0.0
Max:~
v15 Min: 19.0.0
Max:~

구성

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

다음은 모든 클라이언트 라이브러리와 다음과 같습니다.

  • 클라이언트 라이브러리 <ph type="x-smartling-placeholder">
      </ph>
    • GOOGLE_ADS_CONFIGURATION_FILE_PATH: 구성 파일의 경로입니다.
  • OAuth2 <ph type="x-smartling-placeholder">
      </ph>
    • 애플리케이션 모드 <ph type="x-smartling-placeholder">
        </ph>
      • GOOGLE_ADS_CLIENT_ID : 이 값을 OAuth2 클라이언트 ID로 설정합니다.
      • GOOGLE_ADS_CLIENT_SECRET : 이 값을 OAuth2 클라이언트 보안 비밀번호로 설정합니다.
      • GOOGLE_ADS_REFRESH_TOKEN : 이 값을 사전 생성된 OAuth2 갱신 토큰으로 설정합니다. (OAuth2 토큰을 재사용하려는 경우). 이 설정은 선택사항입니다.
    • 서비스 계정 모드 <ph type="x-smartling-placeholder">
        </ph>
      • GOOGLE_ADS_JSON_KEY_FILE_PATH : 이 값을 OAuth2 JSON 구성으로 설정합니다. 파일 경로를 지정합니다.
      • GOOGLE_ADS_IMPERSONATED_EMAIL : 이 값을 확인할 수 있습니다.
  • Google Ads API <ph type="x-smartling-placeholder">
      </ph>
    • GOOGLE_ADS_DEVELOPER_TOKEN : 개발자 토큰으로 설정합니다.
    • GOOGLE_ADS_LOGIN_CUSTOMER_ID : 사용할 승인된 고객의 고객 ID입니다. 하이픈 (-) 없이 요청에 포함됩니다.
    • GOOGLE_ADS_LINKED_CUSTOMER_ID : 이 헤더는 항목 리소스의 Google Ads UI (Google Ads API의 AccountLink 리소스) 이 값 설정 를 지정할 수 있습니다. 하이픈 (-) 없이 설정해야 합니다. 자세히 알아보기 자세한 내용은 고객센터를 참조하세요.
를 통해 개인정보처리방침을 정의할 수 있습니다.

환경 변수는 일반적으로 다음과 같은 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

검색 페이지로 나누기

GoogleAdsService.Search는 일반적으로 다음과 같습니다. 검색결과 페이지를 표시하는 양방향 앱에 사용됩니다.

Google의 클라이언트 라이브러리는 자동으로 구현하는 페이징을 익힐 수 있도록 결과를 반복할 때 순차적으로 다운로드하여 한 번에 처리합니다. 예를 들면 다음과 같습니다.

자바

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
    // Constructs the SearchGoogleAdsStreamRequest.
    SearchGoogleAdsStreamRequest request =
        SearchGoogleAdsStreamRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setQuery(query)
            .build();

    // Creates and issues a search Google Ads stream request that will retrieve all campaigns.
    ServerStream<SearchGoogleAdsStreamResponse> stream =
        googleAdsServiceClient.searchStreamCallable().call(request);

    // Iterates through and prints all of the results in the stream response.
    for (SearchGoogleAdsStreamResponse response : stream) {
      for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
        System.out.printf(
            "Campaign with ID %d and name '%s' was found.%n",
            googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
      }
    }
  }
}
      

C#

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

    // Create a query that will retrieve all campaigns.
    string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

    try
    {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                        googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                }
            }
        );
    }
    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)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves all campaigns.
    $query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
    // Issues a search stream request.
    /** @var GoogleAdsServerStreamDecorator $stream */
    $stream = $googleAdsServiceClient->searchStream(
        SearchGoogleAdsStreamRequest::build($customerId, $query)
    );

    // Iterates over all rows in all messages and prints the requested field values for
    // the campaign in each row.
    foreach ($stream->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getCampaign()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
      

Ruby

def get_campaigns(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

  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
  )

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

Perl

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

  # Create a search Google Ads stream request that will retrieve all campaigns.
  my $search_stream_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      =>
        "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
    });

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

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print the requested
  # field values for the campaign in each row.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      printf "Campaign with ID %d and name '%s' was found.\n",
        $google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
    });

  return 1;
}
      

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

  • 가져올 페이지 수를 최적화합니다.
  • 언제든지 한 번에 저장되는 결과의 양을 최적화할 수 있습니다.
  • 특정 순서로 결과의 페이지를 다운로드하고 처리합니다.

결과 대신 페이지 토큰을 저장하면 더 복잡해질 수 있습니다

코드 예시

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