Page Summary
-
The Google Ads API client library can be configured at runtime using a
GoogleAdsConfigobject. -
Alternative configuration options are available by adding a Nuget reference to
Google.Ads.GoogleAds.Extensions. -
Configuration settings can be loaded from
App.config, a separateApp.configfile, a custom JSON file,settings.json, environment variables, or a generic stream. -
Configuration fields include connectivity settings, OAuth2 settings, transportation settings, and Google Ads API specific settings like
DeveloperTokenandLoginCustomerId.
The Google Ads API client library provides several configuration settings that you can use to customize the library behavior.
Configure the library at runtime
The preferred way to configure the client library is to initialize a
GoogleAdsConfig object at runtime:
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.APPLICATION,
OAuth2ClientId = "INSERT_CLIENT_ID.apps.googleusercontent.com",
OAuth2ClientSecret = "INSERT_CLIENT_SECRET",
OAuth2RefreshToken = "INSERT_REFRESH_TOKEN"
};
GoogleAdsClient client = new GoogleAdsClient(config);
Alternate configuration options
The library also provides additional options to load configuration settings. To
enable them, add a NuGet reference to the
Google.Ads.GoogleAds.Extensions package in your project.
If you use one of these options, configuration settings are not picked up
automatically; you must explicitly load them as shown in the following
sections. Make sure to handle file I/O exceptions (such as
FileNotFoundException or UnauthorizedAccessException) when loading settings
from external files or streams.
Use App.config
All the settings specific to the Google Ads API are stored in the GoogleAdsApi node
of the App.config file. A typical configuration App.config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="GoogleAdsApi"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<GoogleAdsApi>
<!-- Set the service timeout in milliseconds. -->
<add key="Timeout" value="2000" />
<!-- Proxy settings for library. -->
<add key="ProxyServer" value="http://localhost:8888" />
<add key="ProxyUser" value="" />
<add key="ProxyPassword" value="" />
<add key="ProxyDomain" value="" />
<!-- OAuth2 settings -->
<add key="OAuth2Mode" value="APPLICATION" />
<add key="OAuth2ClientId"
value="INSERT_CLIENT_ID.apps.googleusercontent.com" />
<add key="OAuth2ClientSecret" value="INSERT_CLIENT_SECRET" />
<add key="OAuth2RefreshToken" value="INSERT_REFRESH_TOKEN" />
</GoogleAdsApi>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
To load configuration settings from an App.config file, call the
LoadFromDefaultAppConfigSection method on a GoogleAdsConfig object:
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromDefaultAppConfigSection();
GoogleAdsClient client = new GoogleAdsClient(config);
Specify a separate App.config file
If you don't want your App.config cluttered, you can move the
library-specific configuration into its own configuration file using the
configSource property:
Specify a
configSourcein yourApp.config. Modify yourApp.configto reference an external configuration file:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="GoogleAdsApi" type="System.Configuration.DictionarySectionHandler" /> </configSections> <GoogleAdsApi configSource="GoogleAdsApi.config" /> </configuration>Specify the contents of your config file. Create another configuration file with the name you specified in
configSource(GoogleAdsApi.config), and move theGoogleAdsApiconfiguration node from yourApp.configinto this file:<?xml version="1.0" encoding="utf-8" ?> <GoogleAdsApi> <!-- More settings. --> </GoogleAdsApi>Update the build rules in your
.csproj. Include the new configuration file in your project and set its Copy to Output Directory property to Copy always. Rebuild and run your project so your application picks up values from the new configuration file.
Use a custom JSON file
You can use an IConfigurationRoot instance to configure the
client library.
Create a JSON file
Create a JSON file named GoogleAdsApi.json that has a similar structure to the
App.config file:
{
"Timeout": "2000",
"ProxyServer": "http://localhost:8888",
"ProxyUser": "",
"ProxyPassword": "",
"ProxyDomain": "",
"OAuth2Mode": "APPLICATION",
"OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
"OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
"OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
}
Load the configuration
Next, load the JSON file into an IConfigurationRoot:
ConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("GoogleAdsApi.json");
IConfigurationRoot configRoot = builder.Build();
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationRoot(configRoot);
GoogleAdsClient client = new GoogleAdsClient(config);
Use settings.json
The process here is similar to using a custom JSON file, except that the keys
should be inside a section named GoogleAdsApi:
{
"GoogleAdsApi": {
"OAuth2Mode": "APPLICATION",
"OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
"OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
"OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
}
}
Next, extract the GoogleAdsApi section from your application's
IConfiguration instance (for example, injected by ASP.NET Core or built with
ConfigurationBuilder):
IConfigurationSection section = configuration.GetSection("GoogleAdsApi");
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationSection(section);
GoogleAdsClient client = new GoogleAdsClient(config);
Alternatively, you can load a settings.json file directly by path with
config.LoadFromSettingsJson(filePath, "GoogleAdsApi"), or from the
GOOGLE_ADS_CONFIGURATION_FILE_PATH environment variable
(EnvironmentVariableNames.CONFIG_FILE_PATH) using
config.TryLoadFromEnvironmentFilePath.
Use environment variables
You can also initialize the GoogleAdsClient using environment variables:
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromEnvironmentVariables();
GoogleAdsClient client = new GoogleAdsClient(config);
See the full list of supported environment variables.
Use a generic stream
You can also load the configuration, or parts of it, from a generic stream, including an encrypted one:
GoogleAdsConfig config = new GoogleAdsConfig()
{
// Set some configuration properties in code.
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
};
// Load your encrypted data from a file and dispose of the streams properly.
using (CryptoStream strm = GetEncryptedCredentialsStream())
using (StreamReader rdr = new StreamReader(strm))
{
// Configure the OAuth credentials from the encrypted stream.
config.LoadOAuth2SecretsFromStream(rdr);
}
GoogleAdsClient client = new GoogleAdsClient(config);
Configuration fields
The following sections list the settings supported by the Google Ads .NET library.
Connectivity settings
Timeout: Use this key to set the service timeout in milliseconds. The default value is set based on themethod_config/timeoutsetting ingoogleads_grpc_service_config.json. Set a lower value if you need to enforce a shorter limit on the maximum time for an API call. You can set the timeout to 2 hours or more, but the API may still time out extremely long-running requests and return aDEADLINE_EXCEEDEDerror.ProxyServer: Set this to the HTTP proxy server URL if you are using a proxy to connect to the internet.ProxyUser: Set this to the username you require to authenticate against the proxy server. Leave this empty if a username is not required.ProxyPassword: Set this to the password ofProxyUserif you set a value forProxyUser.ProxyDomain: Set this to the domain forProxyUserif your proxy server requires one to be set.MaxReceiveMessageLengthInBytes: Use this setting to increase the maximum size of the API response that the client library can handle. The default value is 64 MB.MaxMetadataSizeInBytes: Use this setting to increase the maximum size of the API error response that the client library can handle. The default value is 16 MB.
Adjust the MaxReceiveMessageLengthInBytes and MaxMetadataSizeInBytes
settings to fix certain ResourceExhausted errors. These settings address
errors of the form:
Status(StatusCode="ResourceExhausted",Detail="Received
message larger than max (423184132 versus 67108864)"
In this example, the error is due to the message size (423184132 bytes)
being larger than what the library can handle (67108864 bytes). Increase
MaxReceiveMessageLengthInBytes to 500000000 to avoid this error. Note
that the error also indicates that your code handled a significantly large
response object (such as a large SearchGoogleAdsResponse).
This could have performance implications for your code due to .NET's
Large Object Heap. If this becomes a performance concern, then you might
have to explore how to reorganize your API calls or redesign parts of your app.
OAuth2 settings
When using OAuth 2.0 to authorize your calls against the Google Ads API servers, you should set the following configuration keys:
AuthorizationMethod: Set toOAuth2.OAuth2Mode: Set toAPPLICATIONorSERVICE_ACCOUNT.OAuth2ClientId: Set this value to your OAuth 2.0 client ID.OAuth2ClientSecret: Set this value to your OAuth 2.0 client secret.OAuth2Scope: Set this value to different scopes if you want to authorize OAuth 2.0 tokens for multiple APIs. This setting is optional.UseApplicationDefaultCredentials: Set this value totrueto authenticate using Application Default Credentials (supported inGoogle.Ads.GoogleAdsv24.1.0and later;config.LoadFromEnvironmentVariables()reads the unprefixedUSE_APPLICATION_DEFAULT_CREDENTIALSenvironment variable).Credentials: (Runtime only, supported inv27.0.0and later) Inject a pre-constructedICredentialorGoogleCredentialinstance directly onGoogleAdsConfigat runtime.
If you're using OAuth2Mode == APPLICATION, then you need to set the following
additional configuration keys:
OAuth2RefreshToken: Set this value to a pre-generated OAuth 2.0 refresh token if you want to reuse OAuth 2.0 tokens. This setting is optional.OAuth2RedirectUri: Set this value to the OAuth 2.0 redirect URL. This setting is optional.
See the following guides for more details:
If you are using OAuth2Mode == SERVICE_ACCOUNT, then you need to set the
following additional configuration keys:
OAuth2SecretsJsonPath: Set this value to the path of the OAuth 2.0 JSON key file.OAuth2PrnEmail: Set this value to the email address of the account you are impersonating when using Google Workspace domain-wide delegation. This setting is optional.
See the OAuth service account flow guide for more details.
Transportation settings
UseGrpcCore: Set this setting totrueto use theGrpc.Corelibrary as the underlying transport layer. See Use theGrpc.Corelibrary.
Google Ads API settings
The following settings are specific to the Google Ads API:
DeveloperToken: Optional inv27.3.0and later (GOOGLE_ADS_DEVELOPER_TOKEN). Developer tokens were sunset on September 9, 2026; on the API server, access levels are determined by your Google Cloud project regardless of client library version, and API servers ignore thedeveloper-tokenheader (until a future major version of the Google Ads API rejects it). To omit or removeDeveloperTokenfrom your configuration, useGoogle.Ads.GoogleAdsv27.3.0or later, which removed local client-sideDeveloperTokenvalidation (earlier versions require a non-emptyDeveloperTokenfor local validation).LoginCustomerId: This is the customer ID of the authorized customer to use in the request, without hyphens (-).LinkedCustomerId: This header is only required for methods that update the resources of an entity when permissioned through Linked Accounts in the Google Ads UI (AccountLinkresource in the Google Ads API). Set this value to the customer ID of the data provider that updates the resources of the specified customer ID. It should be set without hyphens (-). Learn more about Linked Accounts.