スタートガイド

このガイドでは、Google Ads API .NET ライブラリの利用方法の概要を説明します。

インストール

クライアント ライブラリのバイナリは、NuGet を使用して配布されます。クライアント ライブラリを使用するには、プロジェクトの Google.Ads.GoogleAds パッケージに Nuget 参照を追加します。

認可を設定する

API 呼び出しを認可するには、クライアント ID、クライアント シークレット、更新トークン、開発者トークンをライブラリに指定する必要があります。

すでに認証情報がある場合...

  • GoogleAdsApi ノードと、configSections ノードの以下の GoogleAdsApi セクションを、GitHub の App.config ファイルから App.config / Web.config ファイルにコピーします。NuGet を使用してパッケージをインストールした場合、これらのノードは App.config / Web.config ファイルに自動的に挿入されます。
  • 開発者トークン、クライアント ID、クライアント シークレット、更新トークンをアプリの App.config / Web.config に含めます。GitHub に含まれる App.config ファイルには詳細が記載されていますが、構成ガイドを参照して詳細を確認したり、別の構成設定を使用したりすることもできます。

認証情報を生成する必要がある場合

  • 開発者トークンをまだ取得していない場合は、開発者トークン ガイドに沿って取得します。
  • OAuth デスクトップ アプリのフロー ガイドに沿って、クライアント ID、クライアント シークレット、更新トークンを生成します。
  • GoogleAdsApi ノードと、configSections ノードの以下の GoogleAdsApi セクションを、GitHub の App.config ファイルから App.config / Web.config ファイルにコピーします。NuGet を使用してパッケージをインストールした場合、これらのノードは App.config / Web.config ファイルに自動的に挿入されます。
  • 開発者トークン、クライアント ID、クライアント シークレット、更新トークンをアプリの App.config / Web.config に含めます。GitHub に含まれる App.config ファイルには詳細が記載されていますが、構成ガイドを参照して詳細を確認したり、別の構成設定を使用したりすることもできます。

API 呼び出しを行う

クライアント ライブラリの基本的な使用方法は次のとおりです。

// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();

// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V17.CampaignService);

// Make more calls to service class.

GoogleAdsClient インスタンスを作成する

Google Ads API .NET ライブラリで最も重要なクラスは GoogleAdsClient クラスです。API 呼び出しに使用できる事前構成済みのサービスクラスを作成できます。GoogleAdsClient は、アプリの App.config / Web.config で指定された設定を使用してユーザー オブジェクトを作成するデフォルト コンストラクタを提供します。さまざまな構成オプションについては、構成ガイドをご覧ください。

// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();

Service を作成する

GoogleAdsClient は、広告サービスの作成に使用できる GetService メソッドを提供します。

CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);
// Now make calls to CampaignService.

サポートされているすべての API バージョンとサービスを列挙した Services クラスを用意しています。GetService メソッドは、サービスの作成時にこれらの列挙型オブジェクトを引数として受け取ります。たとえば、Google Ads API のバージョン V17CampaignServiceClient のインスタンスを作成するには、上記のように、Services.V17.CampaignService を引数として GoogleAdsClient.GetService メソッドを呼び出す必要があります。

スレッドの安全性

複数のスレッド間で GoogleAdsClient インスタンスを共有することは安全ではありません。1 つのスレッドでインスタンスに対して行った構成の変更が、他のスレッドで作成するサービスに影響する可能性があるためです。GoogleAdsClient インスタンスからの新しいサービス インスタンスの取得、複数のサービスの並列呼び出しなどのオペレーションはスレッドセーフです。

マルチスレッド アプリケーションは次のようになります。

GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();

Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);

userThread1.start(client1);
userThread2.start(client2);

userThread1.join();
userThread2.join();

public void addAdGroups(object data) {
  GoogleAdsClient client = (GoogleAdsClient) data;
  // Do more operations here.
  ...
}

.NET Framework アプリケーションのフリーズを回避する

同期メソッドを使用すると、.NET Framework アプリケーションの一部がフリーズすることがあります。一般的な例は、WinForm アプリケーションのイベント ハンドラ メソッドから API 呼び出しを行うことです。

この問題に対処するには、次の 2 つの方法があります。

  1. 以前の gRPC ライブラリを使用します。

    GoogleAdsConfigUseGrpcCore プロパティを設定して、デフォルトの Grpc.Net.Client ライブラリではなく、以前の Grpc.Core ライブラリを使用できます。この方法は .NET Framework アプリケーションで広範囲にテストされていないため、問題が解決しない可能性があります。スニペットの例を次に示します。

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    
  2. 非同期メソッドを使用します。

    非同期メソッドを使用すると、フリーズを回避できます。次に例を示します。

    SearchStream

    SearchStream() の呼び出しが実行され、結果がリストビューに入力されます。

    private async void button1_Click(object sender, EventArgs e)
    {
    // 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";
     
    List items = new List();
    Task t =  googleAdsService.SearchStreamAsync(customerId.ToString(), query,
        delegate (SearchGoogleAdsStreamResponse resp)
        {
            foreach (GoogleAdsRow googleAdsRow in resp.Results)
            {
                ListViewItem item = new ListViewItem();
                item.Text = googleAdsRow.Campaign.Id.ToString();
                item.SubItems.Add(googleAdsRow.Campaign.Name);
                items.Add(item);
            }
        }
    );
    await t;
    listView1.Items.AddRange(items.ToArray());
    }
    

    キャンペーンの予算

    CampaignBudget の呼び出しが作成され、MessageBox アラートを使用して新しい予算のリソース名が表示されます。

    private async void button2_Click(object sender, EventArgs e)
    {
    // Get the BudgetService.
    CampaignBudgetServiceClient budgetService = client.GetService(
        Services.V17.CampaignBudgetService);
     
    // Create the campaign budget.
    CampaignBudget budget = new CampaignBudget()
    {
        Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
        DeliveryMethod = BudgetDeliveryMethod.Standard,
        AmountMicros = 500000
    };
     
    // Create the operation.
    CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
    {
        Create = budget
    };
     
    // Create the campaign budget.
    Task t = budgetService.MutateCampaignBudgetsAsync(
        customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
     
    await t;
    MutateCampaignBudgetsResponse response = t.Result;
    MessageBox.Show(response.Results[0].ResourceName);
    }
    

非同期メソッドのキャンセル

非同期プログラミングでは、callSettings パラメータを使用して CancellationToken を渡すことができます。

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(3000);
CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);

string query = "SELECT campaign.name FROM campaign";
var request = new SearchGoogleAdsStreamRequest()
{
    CustomerId = customerId.ToString(),
    Query = query,
};

GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V17.GoogleAdsService);

googleAdsService.SearchStream(request,
    delegate (SearchGoogleAdsStreamResponse resp)
    {
        foreach (GoogleAdsRow googleAdsRow in resp.Results)
        {
            // Process the row.
        }
    }, callSettings
);

エラー処理

すべての API 呼び出しが成功するとは限りません。なんらかの理由で API 呼び出しが失敗した場合、サーバーはエラーをスローできます。API エラーをキャプチャして適切に処理することが重要です。

GoogleAdsException インスタンスは、API エラーが発生するとスローされます。問題を特定するための詳細情報が表示されます。

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);

// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    // More fields to update.
    // ...
};

// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
    Update = campaignToUpdate,
    UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};

try
{
    // Update the campaign.
    MutateCampaignsResponse response = campaignService.MutateCampaigns(
        customerId.ToString(), new CampaignOperation[] { operation });

    // Display the results.
    // ...
}
catch (GoogleAdsException e)
{
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");

    // Can examine to get more error details.
    Console.WriteLine($"Failure: {e.Failure}");

    // Can be shared with Google for further troubleshooting.
    Console.WriteLine($"Request ID: {e.RequestId}");
}