This guide gives a brief overview of how to get started with the Google Ads API .NET library.
Installation
The client library binaries are distributed using NuGet. Add a NuGet reference
to the Google.Ads.GoogleAds
package in your project to use
the client library.
Set up authorization
To authorize your API calls, you need to specify your client ID, client secret, refresh token, and developer token to the library.
If you need to generate credentials
- Follow the Developer token guide to obtain your developer token, if you don't already have one.
- Follow the OAuth desktop app flow guide to generate a client ID, client secret, and refresh token.
If you already have credentials
- Copy the
GoogleAdsApi
node and theGoogleAdsApi
section under theconfigSections
node from theApp.config
file in GitHub into yourApp.config
/Web.config
file. If you used NuGet to install the package, these nodes will be automatically inserted into yourApp.config
/Web.config
file. - Include the developer token, the client ID, client secret, and refresh token
in your app's
App.config
/Web.config
.
The App.config
file included in GitHub is well-documented, but you can also refer to the
Configuration guide
to learn more as well as use alternate ways to configure the client library,
such as environment variables.
Make an API call
The basic usage of the client library is as follows:
// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V18.CampaignService);
// Make more calls to service class.
Create a GoogleAdsClient instance
The most important classes in the Google Ads API .NET library is the
GoogleAdsClient
class. It lets you create a pre-configured service class
that can be used for making API calls. GoogleAdsClient
provides a default
constructor that creates a user object using the settings specified in your
app's App.config
/ Web.config
. Refer to the Configuration
guide for configuration
options.
// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();
Create a service
GoogleAdsClient
provides a GetService
method that can be used to create an
Ads service.
CampaignServiceClient campaignService = client.GetService(Services.V18.CampaignService);
// Now make calls to CampaignService.
We provide a Services
class that enumerates all the supported API versions and
services. The GetService
method accepts these enumeration objects as argument
when creating the service. For example, to create an instance of
CampaignServiceClient
for version V18
of the Google Ads API,
you need to call GoogleAdsClient.GetService
method with
Services.V18.CampaignService
as the argument, as shown
in the previous example.
Thread safety
It is not safe to share a GoogleAdsClient
instance between multiple threads,
since the configuration changes you make on an instance in one thread might
affect the services you create on other threads. Operations like obtaining
new service instances from a GoogleAdsClient
instance and making calls to
multiple services in parallel are thread-safe.
A multithreaded application would look something like this:
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.
...
}
Avoid freezes in .NET Framework applications
Synchronous methods can cause some of your .NET Framework applications to freeze. A common example is making API calls from an event handler method of a WinForm application.
There are two ways to address this issue:
Use the legacy Grpc library.
You can set the
UseGrpcCore
property ofGoogleAdsConfig
to use the legacyGrpc.Core
library instead of the defaultGrpc.Net.Client
library. This method has not been tested extensively on .NET Framework applications, so it might not solve the issue. Here is a sample snippet:GoogleAdsConfig config = new GoogleAdsConfig(); config.UseGrpcCore = true; GoogleAdsClient client = new GoogleAdsClient(config);
Use asynchronous methods.
You can use asynchronous methods to avoid freezes. Here are some examples:
SearchStream
A call to
SearchStream()
is performed, and the results are populated into a list view.private async void button1_Click(object sender, EventArgs e) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V18.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()); } Campaign Budget
A CampaignBudget call is created, and the resource name of the new budget is displayed using a
MessageBox
alert.private async void button2_Click(object sender, EventArgs e) { // Get the BudgetService. CampaignBudgetServiceClient budgetService = client.GetService( Services.V18.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); }
Error handling
Not every API call will succeed. The server can throw errors if your API calls fail for some reason. It is important to capture API errors and handle them appropriately.
A GoogleAdsException
instance is thrown when an API error occurs. It has
details to help you figure out what went wrong:
// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V18.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}");
}