클라이언트 라이브러리

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에서 보기

커뮤니티 라이브러리

Google에서는 오픈소스 커뮤니티에서 유지관리하는 여러 라이브러리를 알고 있습니다. 관심 있는 개발자가 이러한 라이브러리를 찾을 수 있도록 이 목록을 유지관리합니다. Google에서는 이러한 라이브러리를 테스트하거나, 기여하거나, 유지관리하지 않습니다. 사용 시 위험은 사용자가 부담합니다. 궁금한 점이 있으면 오픈소스 프로젝트 소유자에게 문의하세요.

Google에서 누락한 라이브러리를 알고 있다면 페이지 상단의 의견 보내기 를 클릭하여 알려주세요.

지원되는 API 버전

표에는 어떤 클라이언트 라이브러리가 어떤 API 버전과 호환되는지 나와 있습니다.

자바

자바용 클라이언트 라이브러리
v24 Min: 43.0.0
Max: -
v23 Min: 42.0.0
Max: -
v22 Min: 41.0.0
Max: -
v21 Min: 39.0.0
Max: -

C#

.NET용 클라이언트 라이브러리
v24 Min: 25.3.0
Max: -
v23 Min: 25.1.0
Max: -
v22 Min: 24.1.0
Max: -
v21 Min: 24.0.0
Max: -

PHP

PHP용 클라이언트 라이브러리
v24 Min: 33.3.0
Max: -
v23 Min: 32.2.0
Max: -
v22 Min: 31.0.0
Max: -
v21 Min: 28.0.0
Max: -

Python

Python용 클라이언트 라이브러리
v24 Min: 30.1.0
Max: -
v23 Min: 29.2.0
Max: -
v22 Min: 28.1.0
Max: -
v21 Min: 28.0.0
Max: -

Ruby

Ruby용 클라이언트 라이브러리
v24 Min: 40.0.0
Max: -
v23 Min: 38.0.0
Max: -
v22 Min: 36.0.0
Max: -
v21 Min: 35.0.0
Max: -

Perl

Perl용 클라이언트 라이브러리
v24 Min: 32.0.0
Max: -
v23 Min: 31.0.0
Max: -
v22 Min: 29.0.0
Max: -
v21 Min: 28.0.0
Max: -

구성

각 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로 설정합니다. 하이픈 (-) 없이 설정해야 합니다. 연결된 계정에 대해 자세히 알아보려면 고객센터를 방문하세요.

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

다음은 터미널을 사용하여 .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.SearchStream 은 일반적으로 항목을 가져오는 데 사용되며 결과는 행 스트림으로 반환됩니다. 또는 불안정한 인터넷 연결을 통해 항목을 가져오는 데 GoogleAdsService.Search를 사용할 수 있습니다. GoogleAdsService.Search 는 페이지당 10,000개의 행으로 고정된 페이지 크기로 결과를 반환합니다.

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

자바

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.V24.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: GoogleAdsClient, customer_id: str) -> None:
    ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")

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

    # Issues a search request using streaming.
    stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
        customer_id=customer_id, query=query
    )

    for batch in stream:
        rows: List[GoogleAdsRow] = batch.results
        for row in rows:
            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::V24::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;
}
      

curl

코드 예시

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