クライアント ライブラリ

クライアント ライブラリでは、概要ビューと基本的な構成要素が提供されます。 アプリを迅速に開発するための Google Ads API 機能。おすすめの方法 API を初めて使用する場合は、1 から始めてください。

クライアント ライブラリ ソース 分布 コードの例
Java google-ads-java Maven, tar.gz GitHub で表示
.NET google-ads-dotnet nugettar.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 バージョンと連携するかを示しています。

Java

Java 用のクライアント ライブラリ
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:

PHP

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 広告の管理画面(Google Ads API の AccountLink リソース)。この値を設定する 組織のリソースを更新するデータ プロバイダのお客様 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

また、コマンドを呼び出すときに環境変数を設定するという方法もあります。 次の 3 点です。

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

検索ページ設定

通常、GoogleAdsService.Search は 結果のページを表示するインタラクティブ アプリで使用されます。

クライアント ライブラリでは、 結果を反復処理する際にページングを それらを順次ダウンロードして一度に処理します。次に例を示します。

Java

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 Maps Platform の Google Ads API。