API 호출

이 가이드에는 이전 단계에서 구성한 몇 가지 기본 요건 설정이 필요합니다. 아직 들어보지 않았다면 소개부터 시작하세요.

또한 이 가이드에서는 갱신 토큰도 사용합니다. 이 워크플로는 Google Ads 계정에 대한 충분한 액세스 권한이 있는 사용자가 일회성 설정으로 앱을 승인하여 사용자의 추가 개입 없이 계정에 오프라인 API 호출을 실행할 수 있는 워크플로입니다. 갱신 토큰을 사용하여 크론 작업 또는 데이터 파이프라인과 같은 오프라인 워크플로와 웹 또는 모바일 앱과 같은 대화형 워크플로를 모두 빌드할 수 있습니다.

갱신 토큰 가져오기

Google Ads API에서는 승인 메커니즘으로 OAuth 2.0을 사용합니다. 기본적으로 OAuth 2.0 인증은 제한된 시간 후에 만료되는 액세스 토큰을 발급합니다. 액세스 토큰을 자동으로 갱신하려면 대신 갱신 토큰을 발행해야 합니다.

  1. oauth2l 도구를 실행하여 갱신 토큰을 생성합니다.

    oauth2l fetch --credentials credentials.json --scope adwords \
        --output_format refresh_token
    

    credentials.json 파일은 이전 단계의 파일입니다.

  2. oauth2l 명령어는 새 브라우저 창에서 Google 계정 로그인 창을 열고 OAuth 2.0 인증 단계를 안내합니다.

    로그인 고객 ID를 식별한 단계의 이메일 주소를 사용하여 로그인해야 합니다.

    앱이 인증되지 않은 경우 경고 화면이 표시될 수 있습니다. 이러한 경우 고급 표시 링크를 클릭하고 PROJECT_NAME (확인되지 않음)으로 이동 옵션을 클릭하는 것이 안전합니다.

  3. 범위를 확인한 후 계속 버튼을 클릭하여 권한을 부여합니다.

    다음 텍스트와 함께 메시지가 브라우저에 표시됩니다.

    Authorization code granted. Please close this tab.
    

    oauth2l 명령어는 다음 JSON 스니펫을 출력합니다.

    {
      "client_id": "******.apps.googleusercontent.com",
      "client_secret": "******",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "refresh_token": "******",
      "type": "authorized_user"
    }
    

API 호출

API 호출 방법에 대한 안내를 보려면 원하는 클라이언트를 선택하세요.

Java

클라이언트 라이브러리 아티팩트는 Maven 중앙 저장소에 게시됩니다. 다음과 같이 클라이언트 라이브러리를 프로젝트에 종속 항목으로 추가합니다.

Maven 종속 항목은 다음과 같습니다.

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads</artifactId>
  <version>30.0.0</version>
</dependency>

Gradle 종속 항목은 다음과 같습니다.

implementation 'com.google.api-ads:google-ads:30.0.0'

다음 콘텐츠로 ~/ads.properties라는 파일을 만듭니다.

api.googleads.clientId=INSERT_CLIENT_ID_HERE
api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE
api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

다음과 같이 GoogleAdsClient 객체를 만듭니다.

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

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

  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#

클라이언트 라이브러리 패키지는 Nuget.org 저장소에 게시됩니다. 먼저 Google.Ads.GoogleAds 패키지에 nuget 참조를 추가합니다.

dotnet add package Google.Ads.GoogleAds --version 18.1.0

관련 설정으로 GoogleAdsConfig 객체를 만들고 이 객체로 GoogleAdsClient 객체를 만듭니다.

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = "APPLICATION",
    OAuth2ClientId = "******.apps.googleusercontent.com",
    OAuth2ClientSecret = "******",
    OAuth2RefreshToken = "******",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

  public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V16.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;
    }
}

2,399필리핀

클라이언트 라이브러리 패키지는 Packagist 저장소에 게시됩니다. 프로젝트의 루트 디렉터리로 변경하고 다음 명령어를 실행하여 프로젝트 루트 디렉터리의 vendor/ 디렉터리에 라이브러리와 모든 종속 항목을 설치합니다.

composer require googleads/google-ads-php:22.0.0

GitHub 저장소에서 google_ads_php.ini 파일의 사본을 만들고 사용자 인증 정보를 포함하도록 수정합니다.

[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"

[OAUTH2]
clientId = "INSERT_OAUTH2_CLIENT_ID_HERE"
clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"

GoogleAdsClient 객체의 인스턴스를 생성합니다.

$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->build();

$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->withOAuth2Credential($oAuth2Credential)
    ->build();

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

  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

PyPI에 배포된 클라이언트 라이브러리는 다음과 같이 pip 명령어를 사용하여 설치할 수 있습니다.

python -m pip install google-ads==21.3.0

GitHub 저장소에서 google-ads.yaml 파일의 사본을 만들고 사용자 인증 정보를 포함하도록 수정합니다.

client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE

GoogleAdsClient.load_from_storage 메서드를 호출하여 GoogleAdsClient 인스턴스를 만듭니다. 메서드를 호출할 때 google-ads.yaml의 경로를 메서드에 문자열로 전달합니다.

from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

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

클라이언트 라이브러리용 Ruby gem은 Rubygems gem 호스팅 사이트에 게시됩니다. 번들러를 사용하여 설치하는 것이 좋습니다. Gemfile에 다음 줄을 추가합니다.

gem 'google-ads-googleads', '~> 23.1.0'

그런 후 다음 명령어를 실행합니다.

bundle install

GitHub 저장소에서 google_ads_config.rb 파일의 사본을 만들고 사용자 인증 정보를 포함하도록 수정합니다.

Google::Ads::GoogleAds::Config.new do |c|
  c.client_id = 'INSERT_CLIENT_ID_HERE'
  c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
  c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
  c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
end

이 파일을 보관할 경로를 전달하여 GoogleAdsClient 인스턴스를 만듭니다.

client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

  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

라이브러리는 CPAN에 배포됩니다. 먼저 원하는 디렉터리에서 google-ads-perl 저장소를 클론합니다.

git clone https://github.com/googleads/google-ads-perl.git

google-ads-perl 디렉터리로 변경하고 명령어 프롬프트에서 다음 명령어를 실행하여 라이브러리를 사용하는 데 필요한 모든 종속 항목을 설치합니다.

cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps

GitHub 저장소에서 googleads.properties 파일의 사본을 만들고 사용자 인증 정보를 포함하도록 수정합니다.

clientId=INSERT_OAUTH2_CLIENT_ID_HERE
clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE
refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

이 파일을 보관할 경로를 전달하여 Client 인스턴스를 만듭니다.

my $properties_file = "/path/to/googleads.properties";

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

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

  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::V16::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;
}

REST

먼저 HTTP 클라이언트를 사용하여 OAuth 2.0 액세스 토큰을 가져옵니다. 이 가이드에서는 curl 명령어를 사용합니다.

curl \
  --data "grant_type=refresh_token" \
  --data "client_id=CLIENT_ID" \
  --data "client_secret=CLIENT_SECRET" \
  --data "refresh_token=REFRESH_TOKEN" \
  https://www.googleapis.com/oauth2/v3/token

그런 다음 GoogleAdsService.SearchStream 메서드를 사용하여 캠페인 보고서를 실행하여 계정에서 캠페인을 검색합니다. 이 가이드에서는 보고의 세부정보는 다루지 않습니다.

curl -i -X POST https://googleads.googleapis.com/v16/customers/CUSTOMER_ID/googleAds:searchStream \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer ACCESS_TOKEN" \
   -H "developer-token: DEVELOPER_TOKEN" \
   -H "login-customer-id: LOGIN_CUSTOMER_ID" \
   --data-binary "@query.json"

query.json의 콘텐츠는 다음과 같습니다.

{
  "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}