スタートガイド

このガイドでは、Google Ads API .NET ライブラリの利用を開始する方法について簡単に説明します。

インストール

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

認可を設定する

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

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

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

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

  • 開発者トークンをまだ取得していない場合は、開発者トークンガイドに沿って取得します。
  • OAuth デスクトップ アプリのフローのガイドに沿って、クライアント ID、クライアント シークレット、更新トークンを生成します。
  • GitHub の App.config ファイルにある GoogleAdsApi ノードと configSections ノードの GoogleAdsApi セクションを 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.V16.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.V16.CampaignService);
// Now make calls to CampaignService.

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

スレッドの安全性

複数のスレッド間で GoogleAdsClient インスタンスを共有すると安全ではありません。あるスレッドでインスタンスに対して行った構成の変更が、他のスレッドで作成したサービスに影響する可能性があるためです。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.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";
     
    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.V16.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.V16.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.V16.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}");
}