### Minimal Google Ads API Interaction Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/README.md Demonstrates initializing the GoogleAdsClient, retrieving a service, making an API call to get a campaign, and handling potential GoogleAdsException errors. ```python from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException # Initialize client from configuration file client = GoogleAdsClient.load_from_storage() try: # Get a service service = client.get_service("CampaignService") # Make an API call campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) print(f"Campaign: {campaign.name}") except GoogleAdsException as ex: print(f"API error: {ex.failure.errors[0].message}") ``` -------------------------------- ### GET Operation Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Illustrates how to fetch a single resource, such as a campaign, using its unique resource name via a GET operation on a service client. ```APIDOC ## GET Operation Example ### Description This example demonstrates how to retrieve a specific Google Ads resource, like a campaign, by providing its `customer_id` and `resource_name` to the service's GET method. ### Method ```python service = client.get_service("CampaignService") # Get a single resource by resource name campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) ``` ``` -------------------------------- ### Complete YAML Configuration Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md A comprehensive example of a YAML configuration file for the Google Ads API client. It includes required fields like developer token and proto plus setting, OAuth2 credentials, and optional settings for customer IDs, endpoint, proxy, and logging. ```yaml # Required developer_token: "INSERT_DEVELOPER_TOKEN_HERE" use_proto_plus: False # OAuth2 Installed App Flow client_id: "INSERT_CLIENT_ID.apps.googleusercontent.com" client_secret: "INSERT_CLIENT_SECRET" refresh_token: "INSERT_REFRESH_TOKEN" # Optional login_customer_id: "1234567890" linked_customer_id: "1234567890" endpoint: "googleads.googleapis.com" http_proxy: "http://user:password@localhost:8080" # Logging (optional) logging: version: 1 disable_existing_loggers: False formatters: default_fmt: format: '[%(asctime)s - %(levelname)s] %(message).5000s' handlers: console: class: logging.StreamHandler formatter: default_fmt loggers: "": handlers: [console] level: INFO ``` -------------------------------- ### Logging Configuration Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Configure logging for the Google Ads API client. This example sets up a stream handler to output logs to the console with a specific format and level. ```yaml logging: version: 1 disable_existing_loggers: False formatters: default_fmt: format: '[%(asctime)s - %(levelname)s] %(message).5000s' datefmt: '%Y-%m-%d %H:%M:%S' handlers: default_handler: class: logging.StreamHandler formatter: default_fmt level: DEBUG loggers: "": handlers: [default_handler] level: INFO google.ads.googleads: level: DEBUG ``` -------------------------------- ### Initialize Installed App Credentials with Proxy Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/oauth2.md Initializes installed app credentials while specifying an HTTP proxy to be used for all network operations, including credential refresh. ```python from google.ads.googleads import oauth2 creds = oauth2.get_installed_app_credentials( client_id="xxx.apps.googleusercontent.com", client_secret="GOCSPX-xxx", refresh_token="1//xxx", http_proxy="http://user:password@localhost:8080" ) ``` -------------------------------- ### Install black formatter Source: https://github.com/googleads/google-ads-python/blob/main/CONTRIBUTING.md Install the required version of the `black` formatter for code styling. This is a prerequisite for running the formatter. ```bash python -m pip install black==19.10b0 ``` -------------------------------- ### Getting Common Service Clients Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Provides examples of how to retrieve clients for various common services, including campaign management, ad groups, assets, search, and account management. ```python # Campaign operations client.get_service("CampaignService") client.get_service("CampaignBudgetService") # Ad group operations client.get_service("AdGroupService") client.get_service("AdGroupAdService") client.get_service("AdGroupCriterionService") # Asset operations client.get_service("AssetService") client.get_service("AssetGroupService") # Search and reporting client.get_service("GoogleAdsService") # Account management client.get_service("CustomerService") ``` -------------------------------- ### Install Google Ads API Client Library Source: https://github.com/googleads/google-ads-python/blob/main/README.rst Install the Google Ads API client library for Python using pip. Ensure you have Python 3.9 or later. ```bash pip install google-ads ``` -------------------------------- ### Async Flow Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Illustrates how to retrieve and use an asynchronous service client, where async interceptors are automatically applied. ```APIDOC ## Async Flow ### Description Shows the sequence of interceptors for asynchronous calls, highlighting that async interceptors are automatically used when `is_async=True` is set. ### Code ```python async def get_campaigns_async(client, customer_id): # Async interceptors automatically used service = client.get_service("GoogleAdsService", is_async=True) response = await service.search( customer_id=customer_id, query="SELECT campaign.id FROM campaign LIMIT 10" ) return response ``` ``` -------------------------------- ### GoogleAdsClient Initialization Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Initializes a GoogleAdsClient instance with credentials and configuration. This is the main way to start using the Google Ads API client library. ```APIDOC ## GoogleAdsClient `__init__` ### Description Initialize a GoogleAdsClient with authentication credentials and configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **credentials** (Credentials) - Required - A `google.auth.credentials.Credentials` instance for authentication - **developer_token** (str) - Required - Your Google Ads API developer token - **endpoint** (Union[str, None]) - Optional - Optional custom API endpoint URL - **login_customer_id** (Union[str, None]) - Optional - Customer ID for manager account login (10-digit string) - **logging_config** (Union[Dict[str, Any], None]) - Optional - Logging configuration dict for `logging.config.dictConfig` - **linked_customer_id** (Union[str, None]) - Optional - Linked customer ID for cross-customer operations (10-digit string) - **version** (Union[str, None]) - Optional - API version (e.g., "v24", "v23"). Defaults to latest supported version - **http_proxy** (Union[str, None]) - Optional - HTTP proxy URL (e.g., "http://user:password@host:port") - **use_proto_plus** (bool) - Optional - If True, use proto-plus message types; if False, use protobuf messages - **use_cloud_org_for_api_access** (Union[str, None]) - Optional - Use Google Cloud Organization instead of developer token (pilot feature) - **ads_assistant** (Union[str, None]) - Optional - Google Ads API Assistant version identifier ### Request Example ```python from google.ads.googleads.client import GoogleAdsClient from google.oauth2.credentials import Credentials # Using installed app credentials creds = Credentials( token=refresh_token, client_id=client_id, client_secret=client_secret, token_uri="https://accounts.google.com/o/oauth2/token" ) client = GoogleAdsClient( credentials=creds, developer_token="YOUR_DEVELOPER_TOKEN", login_customer_id="1234567890", version="v24" ) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### SEARCH Operation Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Shows how to search for resources that match specified criteria using a Google Ads Query Language (GAQL) query with the `search` method. ```APIDOC ## SEARCH Operation Example ### Description This snippet illustrates how to use the `search` method, typically on the `GoogleAdsService`, to find resources matching a given GAQL query. It also shows how to iterate through the results. ### Method ```python service = client.get_service("GoogleAdsService") # Search for resources matching criteria response = service.search( customer_id="1234567890", query="SELECT campaign.id, campaign.name FROM campaign" ) for row in response.results: print(f"Campaign: {row.campaign.name}") ``` ``` -------------------------------- ### Custom Interceptor Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Demonstrates how to create and use a custom gRPC interceptor when retrieving a service. ```APIDOC ## Using Custom Interceptors ### Description Custom interceptors can be passed when retrieving a service to modify request/response behavior. ### Method `GoogleAdsClient.get_service(service_name, interceptors=[...])` ### Parameters #### Path Parameters - **service_name** (str) - Required - The name of the service to retrieve. - **interceptors** (list[Interceptor]) - Optional - A list of custom interceptor instances to apply. ### Request Example ```python from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.interceptors import Interceptor import grpc # Create a custom interceptor class CustomInterceptor(grpc.UnaryUnaryClientInterceptor): def intercept_unary_unary( self, continuation, client_call_details, request ): # Your custom logic here return continuation(client_call_details, request) client = GoogleAdsClient.load_from_storage() service = client.get_service( "CampaignService", interceptors=[CustomInterceptor()] ) ``` ``` -------------------------------- ### Load Google Ads Client from Storage Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/oauth2.md Loads the Google Ads API client using default configuration, typically from a google-ads.yaml file. This is a common setup for both Installed Application and Service Account flows. ```python from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_storage() # Uses google-ads.yaml service = client.get_service("CampaignService") ``` -------------------------------- ### Initialize Credentials using Configuration Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/oauth2.md Automatically selects and initializes the correct credential type based on the provided configuration dictionary. Supports Application Default Credentials, installed app credentials, and service account credentials. ```python from google.ads.googleads import oauth2 # Configuration with installed app credentials config = { "client_id": "xxx.apps.googleusercontent.com", "client_secret": "GOCSPX-xxx", "refresh_token": "1//xxx", } creds = oauth2.get_credentials(config) ``` -------------------------------- ### Example: SearchStream (Unary-Stream) Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Demonstrates a unary-stream API call pattern, where a single request yields a stream of responses. This is used for fetching potentially large result sets. ```python # Example: SearchStream stream = service.search_stream( customer_id=customer_id, query=query ) for batch in stream: for row in batch.results: print(row) ``` -------------------------------- ### SEARCH_STREAM Operation Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Demonstrates how to efficiently retrieve large datasets by streaming results using the `search_stream` method, which avoids the need for manual pagination. ```APIDOC ## SEARCH_STREAM Operation Example ### Description This example shows how to use the `search_stream` method, typically on the `GoogleAdsService`, to retrieve results in batches, which is ideal for handling large datasets without managing pagination tokens. ### Method ```python service = client.get_service("GoogleAdsService") # Stream results for large datasets stream = service.search_stream( customer_id="1234567890", query="SELECT campaign.id, campaign.name FROM campaign" ) for batch in stream: for row in batch.results: print(f"Campaign: {row.campaign.name}") ``` ``` -------------------------------- ### get_oauth2_installed_app_keys Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Retrieves the required keys for the OAuth2 installed application flow. Returns a tuple of key names. ```APIDOC ## `get_oauth2_installed_app_keys` ### Description Get the required keys for OAuth2 installed application flow. ### Method Signature ```python def get_oauth2_installed_app_keys() -> tuple[str, ...] ``` ### Returns Tuple of required key names: `("client_id", "client_secret", "refresh_token")` ``` -------------------------------- ### Google Ads Configuration File Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Example of a YAML configuration file for the Google Ads client. It includes required fields like developer token and OAuth2 credentials, as well as optional settings. ```yaml # Required fields developer_token: "INSERT_DEVELOPER_TOKEN_HERE" use_proto_plus: False # or True # OAuth2 Installed App Flow client_id: "INSERT_OAUTH2_CLIENT_ID_HERE" client_secret: "INSERT_OAUTH2_CLIENT_SECRET_HERE" refresh_token: "INSERT_REFRESH_TOKEN_HERE" # OR OAuth2 Service Account Flow # json_key_file_path: "INSERT_PATH_TO_JSON_KEY_FILE_HERE" # impersonated_email: "INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT" # Optional fields login_customer_id: "INSERT_LOGIN_CUSTOMER_ID_HERE" linked_customer_id: "INSERT_LINKED_CUSTOMER_ID_HERE" endpoint: "custom.endpoint.com" http_proxy: "http://user:password@host:port" use_application_default_credentials: False # Logging configuration (optional) # logging: # version: 1 # disable_existing_loggers: False # handlers: # console: # class: logging.StreamHandler # loggers: # "": # handlers: [console] # level: INFO ``` -------------------------------- ### Programmatic Google Ads Client Configuration Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/quick-start.md Initializes the Google Ads API client by providing credentials and configuration details programmatically. This offers fine-grained control over client setup. ```python from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads import oauth2 from google.oauth2.credentials import Credentials # Create credentials programmatically creds = oauth2.get_installed_app_credentials( client_id="xxx.apps.googleusercontent.com", client_secret="GOCSPX-xxx", refresh_token="1//xxx" ) # Initialize client client = GoogleAdsClient( credentials=creds, developer_token="xxx", login_customer_id="1234567890", version="v24" ) # Use client... service = client.get_service("CampaignService") ``` -------------------------------- ### Adjusting Logging Levels for Production Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Minimize overhead in production by adjusting the logging level for the google.ads.googleads library. This example sets the level to WARNING, disabling debug logging. ```python # Disable debug logging in production logging.getLogger('google.ads.googleads').setLevel(logging.WARNING) ``` -------------------------------- ### Async Request Processing Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Illustrates how to make an asynchronous API call using the Google Ads API client. Async interceptors are automatically utilized in this flow. ```python async def get_campaigns_async(client, customer_id): # Async interceptors automatically used service = client.get_service("GoogleAdsService", is_async=True) response = await service.search( customer_id=customer_id, query="SELECT campaign.id FROM campaign LIMIT 10" ) return response ``` -------------------------------- ### Common GAQL Queries for GoogleAdsService Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Provides examples of common Google Ads Query Language (GAQL) strings used with the GoogleAdsService for retrieving various entities like campaigns, ad groups, and ads. ```sql # Get all campaigns "SELECT campaign.id, campaign.name, campaign.status FROM campaign" # Get campaigns with specific status "SELECT campaign.id, campaign.name FROM campaign WHERE campaign.status = 'ENABLED'" # Get ad groups in a campaign "SELECT ad_group.id, ad_group.name FROM ad_group WHERE campaign.id = 123456789" # Get all ads "SELECT ad.id, ad.name, ad_group.id FROM ad" ``` -------------------------------- ### Get OAuth2 Installed App Keys Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Retrieves the required key names for the OAuth2 installed application flow. Use this to understand which credentials are needed for user-based authentication. ```python def get_oauth2_installed_app_keys() -> tuple[str, ...] ``` -------------------------------- ### Access Google Ads API Services Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Retrieve service clients for interacting with specific Google Ads API services. You can get synchronous or asynchronous clients and specify the API version. The example shows how to get a CampaignService and a GoogleAdsService client. ```python # Get a synchronous service client campaign_service = client.get_service("CampaignService") # Get an asynchronous service client google_ads_service = client.get_service("GoogleAdsService", is_async=True) # Use the service response = campaign_service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) ``` -------------------------------- ### Initialize GoogleAdsClient from YAML String Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Use this method to create a GoogleAdsClient instance by providing a YAML configuration as a string. Ensure the YAML includes necessary credentials and settings. The API version can be optionally specified. ```python yaml_config = """ developer_token: \"xxx...\" client_id: \"xxx...\" client_secret: \"xxx...\" refresh_token: \"xxx...\" use_proto_plus: False """ client = GoogleAdsClient.load_from_string(yaml_config, version="v24") ``` -------------------------------- ### Configure Google Ads Client with Environment Variables Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/quick-start.md Sets up the Google Ads API client using environment variables for authentication and configuration. This method avoids the need for a YAML configuration file. ```bash export GOOGLE_ADS_DEVELOPER_TOKEN="xxx..." export GOOGLE_ADS_CLIENT_ID="xxx..." export GOOGLE_ADS_CLIENT_SECRET="xxx..." export GOOGLE_ADS_REFRESH_TOKEN="xxx..." export GOOGLE_ADS_USE_PROTO_PLUS="False" export GOOGLE_ADS_LOGIN_CUSTOMER_ID="1234567890" ``` -------------------------------- ### Initialize GoogleAdsClient from Dictionary Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Create a GoogleAdsClient instance by passing a configuration dictionary. This is an alternative to using a YAML string for initialization. The API version can be optionally specified. ```python config = { "developer_token": "xxx...", "client_id": "xxx...", "client_secret": "xxx...", "refresh_token": "xxx...", "use_proto_plus": False, } client = GoogleAdsClient.load_from_dict(config) ``` -------------------------------- ### Get Installed App Credentials Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/oauth2.md Use this function for applications that authenticate on behalf of individual users via the OAuth2 authorization code flow. It requires client ID, client secret, and a refresh token. ```python from google.ads.googleads import oauth2 creds = oauth2.get_installed_app_credentials( client_id="123456789.apps.googleusercontent.com", client_secret="GOCSPX-xxx...", refresh_token="1//xxx..." ) # Use credentials with GoogleAdsClient from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient( credentials=creds, developer_token="YOUR_DEVELOPER_TOKEN" ) ``` -------------------------------- ### GoogleAdsClient.load_from_env Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Creates a GoogleAdsClient instance using configuration from environment variables. Environment variables must be prefixed with GOOGLE_ADS_. ```APIDOC ## GoogleAdsClient `load_from_env` ### Description Create a GoogleAdsClient from environment variables. ### Method classmethod ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **version** (Union[str, None]) - Optional - API version to use ### Request Example ```python import os os.environ["GOOGLE_ADS_DEVELOPER_TOKEN"] = "xxx..." os.environ["GOOGLE_ADS_CLIENT_ID"] = "xxx..." os.environ["GOOGLE_ADS_CLIENT_SECRET"] = "xxx..." os.environ["GOOGLE_ADS_REFRESH_TOKEN"] = "xxx..." os.environ["GOOGLE_ADS_USE_PROTO_PLUS"] = "False" client = GoogleAdsClient.load_from_env(version="v24") ``` ### Response #### Success Response (200) - **GoogleAdsClient** - A configured `GoogleAdsClient` instance #### Response Example None ### Raises - `ValueError` — If required environment variables are missing ``` -------------------------------- ### Efficient Campaign Creation with Template Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/advanced-patterns.md Demonstrates efficient campaign creation by reusing a template operation object. Avoids the overhead of creating a new operation object for each campaign. ```python # Inefficient - creates type for every campaign def create_campaigns_inefficient(service, names): results = [] for name in names: operation = client.get_type("CampaignOperation") # Called every time operation.create.name = name results.append(operation) return results # Efficient - reuse template def create_campaigns_efficient(service, names): results = [] template = client.get_type("CampaignOperation") for name in names: operation = client.get_type("CampaignOperation") operation.create.name = name results.append(operation) return results ``` -------------------------------- ### Get a Campaign Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Retrieves a specific campaign using its resource name. Requires the CampaignService. ```python service = client.get_service("CampaignService") campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) print(f"Name: {campaign.name}") print(f"Status: {campaign.status}") print(f"Budget: {campaign.campaign_budget}") ``` -------------------------------- ### Protobuf Message Creation and Serialization Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/types-and-messages.md Shows how to create a `Campaign` message using the standard Protobuf format and demonstrates serialization using `SerializeToString()`. ```python client = GoogleAdsClient( credentials=creds, developer_token=token, use_proto_plus=False ) campaign = client.get_type("Campaign") # Protobuf messages use similar syntax but are less Pythonic campaign.id = 123456789 campaign.name = "My Campaign" # Has additional methods like SerializeToString, ParseFromString, etc. serialized = campaign.SerializeToString() ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Loads configuration from environment variables prefixed with GOOGLE_ADS_. If GOOGLE_ADS_CONFIGURATION_FILE_PATH is set, it loads from the specified YAML file instead. ```python import os from google.ads.googleads import config os.environ["GOOGLE_ADS_DEVELOPER_TOKEN"] = "xxx..." os.environ["GOOGLE_ADS_CLIENT_ID"] = "xxx..." os.environ["GOOGLE_ADS_CLIENT_SECRET"] = "xxx..." os.environ["GOOGLE_ADS_REFRESH_TOKEN"] = "xxx..." os.environ["GOOGLE_ADS_USE_PROTO_PLUS"] = "False" cfg = config.load_from_env() ``` -------------------------------- ### Getting a Campaign Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Retrieves a specific campaign using its resource name. This is useful for fetching campaign details to display or to use in further operations. ```APIDOC ## Get Campaign ### Description Retrieves a specific campaign by its resource name. ### Method `get_campaign` ### Parameters - **customer_id** (string) - Required - The ID of the customer. - **resource_name** (string) - Required - The resource name of the campaign to retrieve. ### Response #### Success Response Returns a `Campaign` object with details about the campaign. ### Request Example ```python service = client.get_service("CampaignService") campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) ``` ``` -------------------------------- ### Load GoogleAdsClient from Storage Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Create a GoogleAdsClient instance by loading configuration from a YAML file. Supports loading from the default location or a custom path, with an option to specify the API version. ```python # Load from default location (~/google-ads.yaml) client = GoogleAdsClient.load_from_storage() # Load from custom path with specific API version client = GoogleAdsClient.load_from_storage( path="/etc/google-ads.yaml", version="v24" ) ``` -------------------------------- ### Access and Use Enums Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/README.md Access categorical values (enums) via `client.enums` and assign them to resource fields. For example, use `client.enums.CampaignStatus.ENABLED`. ```python # Access enums status = client.enums.CampaignStatus.ENABLED device = client.enums.DeviceType.MOBILE # Use in messages campaign.status = client.enums.CampaignStatus.PAUSED ``` -------------------------------- ### Get a Service Client Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/README.md Retrieve a service client for interacting with specific Google Ads API services. This is the entry point for most API operations. ```python service = client.get_service("CampaignService") campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/123456789" ) ``` -------------------------------- ### Get OAuth2 Service Account Keys Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Retrieves the required key names for the OAuth2 service account flow. This is used for server-to-server authentication. ```python def get_oauth2_required_service_account_keys() -> tuple[str, ...] ``` -------------------------------- ### Initialize GoogleAdsClient with Credentials Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Initialize a GoogleAdsClient instance using OAuth2 credentials and a developer token. Specify the login customer ID and API version as needed. ```python from google.ads.googleads.client import GoogleAdsClient from google.oauth2.credentials import Credentials # Using installed app credentials creds = Credentials( token=refresh_token, client_id=client_id, client_secret=client_secret, token_uri="https://accounts.google.com/o/oauth2/token" ) client = GoogleAdsClient( credentials=creds, developer_token="YOUR_DEVELOPER_TOKEN", login_customer_id="1234567890", version="v24" ) ``` -------------------------------- ### get_installed_app_credentials Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/oauth2.md Creates credentials for the OAuth2 installed application flow, suitable for applications authenticating on behalf of individual users via the OAuth2 authorization code flow. ```APIDOC ## get_installed_app_credentials ### Description Create credentials for the OAuth2 installed application flow. Used for applications that authenticate on behalf of individual users via the OAuth2 authorization code flow. ### Method `get_installed_app_credentials` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **client_id** (str) - Required - OAuth2 client ID from Google Cloud Console - **client_secret** (str) - Required - OAuth2 client secret from Google Cloud Console - **refresh_token** (str) - Required - OAuth2 refresh token obtained from user authorization - **http_proxy** (Union[str, None]) - Optional - HTTP proxy URL (e.g., "http://user:password@host:port") - **token_uri** (str) - Optional - OAuth2 token endpoint URL (Default: "https://accounts.google.com/o/oauth2/token") ### Returns `google.oauth2.credentials.Credentials` instance initialized and refreshed ### Raises - `ValueError` — If credentials are invalid or can't be refreshed - `Exception` — If network error occurs during credential refresh ### Example ```python from google.ads.googleads import oauth2 creds = oauth2.get_installed_app_credentials( client_id="123456789.apps.googleusercontent.com", client_secret="GOCSPX-xxx...", refresh_token="1//xxx..." ) from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient( credentials=creds, developer_token="YOUR_DEVELOPER_TOKEN" ) ``` ``` -------------------------------- ### Initialize LoggingInterceptor Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Initializes the LoggingInterceptor with necessary configuration details. Requires a logger instance, API version, and endpoint URL. ```python def __init__( self, logger: logging.Logger, api_version: str, endpoint: str, ): """Initialize LoggingInterceptor. Args: logger: Python logger instance for output. api_version: Google Ads API version. endpoint: API endpoint URL. """ ``` -------------------------------- ### Accessing Enums via Client Accessor Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/types-and-messages.md Illustrates how to access enumeration values directly through the `client.enums` property, providing a convenient way to get enum constants. ```python client = GoogleAdsClient.load_from_storage() # Access enums via the client.enums property status = client.enums.CampaignStatus.ENABLED # Equivalent to: from google.ads.googleads.v24.enums.types import CampaignStatus as CampaignStatusEnum status = CampaignStatusEnum.ENABLED ``` -------------------------------- ### Load Google Ads Client from Environment Variables Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/quick-start.md Initializes the Google Ads API client after environment variables have been set. This is a convenient way to configure the client for development or testing. ```python from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_env() ``` -------------------------------- ### MUTATE Operation Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Explains how to perform create, update, or delete operations on resources by constructing an operation object and sending it via the `mutate` method of a service. ```APIDOC ## MUTATE Operation Example ### Description This snippet demonstrates how to create, update, or delete Google Ads resources. It involves creating an operation object (e.g., `CampaignOperation`) and sending it to the appropriate mutate method of a service. ### Method ```python service = client.get_service("CampaignService") # Create, update, or delete resources operation = client.get_type("CampaignOperation") operation.create.name = "New Campaign" response = service.mutate_campaigns( customer_id="1234567890", operations=[operation] ) for result in response.results: print(f"Created: {result.resource_name}") ``` ``` -------------------------------- ### Create Multiple Campaigns Efficiently Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/quick-start.md Demonstrates how to create a large number of campaigns in a single API call for improved efficiency. This is useful for bulk operations. ```python from google.ads.googleads.client import GoogleAdsClient def main(): client = GoogleAdsClient.load_from_storage() service = client.get_service("CampaignService") operations = [] # Prepare multiple operations for i in range(100): operation = client.get_type("CampaignOperation") operation.create.name = f"Campaign {i}" operation.create.status = client.enums.CampaignStatus.ENABLED operation.create.advertising_channel_type = ( client.enums.AdvertisingChannelType.SEARCH ) operations.append(operation) # Send all at once (more efficient than individual API calls) response = service.mutate_campaigns( customer_id="1234567890", operations=operations ) print(f"Created {len(response.results)} campaigns") if __name__ == "__main__": main() ``` -------------------------------- ### GoogleAdsClient.load_from_storage Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Creates a GoogleAdsClient instance from a YAML configuration file. It can load from a default path or a custom path. ```APIDOC ## GoogleAdsClient `load_from_storage` ### Description Create a GoogleAdsClient from a YAML configuration file. ### Method classmethod ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (Union[str, None]) - Optional - Path to YAML config file. If None, defaults to `~/google-ads.yaml` - **version** (Union[str, None]) - Optional - API version to use. If None, uses default version ### Request Example ```python # Load from default location (~/google-ads.yaml) client = GoogleAdsClient.load_from_storage() # Load from custom path with specific API version client = GoogleAdsClient.load_from_storage( path="/etc/google-ads.yaml", version="v24" ) ``` ### Response #### Success Response (200) - **GoogleAdsClient** - A configured `GoogleAdsClient` instance #### Response Example None ### Raises - `FileNotFoundError` — If the configuration file doesn't exist - `IOError` — If the configuration file can't be read - `ValueError` — If the configuration is invalid or missing required fields ``` -------------------------------- ### Example: GetCampaign (Unary-Unary) Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md A standard synchronous API call pattern where a single request is sent and a single response is received. This is typical for retrieving a specific resource. ```python # Example: GetCampaign response = service.get_campaign( customer_id=customer_id, resource_name=campaign_resource_name ) ``` -------------------------------- ### Initialize MetadataInterceptor Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Initializes the MetadataInterceptor with developer token and optional customer IDs or access configurations. ```python def __init__( self, developer_token: str, login_customer_id: Optional[str] = None, linked_customer_id: Optional[str] = None, use_cloud_org_for_api_access: Optional[bool] = None, ads_assistant: Optional[str] = None, ): """Initialize MetadataInterceptor. Args: developer_token: Your Google Ads API developer token. login_customer_id: Manager account customer ID (optional). linked_customer_id: Linked customer ID (optional). use_cloud_org_for_api_access: Use Cloud Organization for access (optional). ads_assistant: Google Ads API Assistant version (optional). """ ``` -------------------------------- ### Working with Repeated Fields (Lists) Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/types-and-messages.md Repeated fields in messages are handled as Python lists. This example shows creating a list of `CampaignOperation` objects and sending them in a `MutateCampaignsRequest`. ```python # Creating a list of operations operations = [] for campaign_name in ["Campaign 1", "Campaign 2", "Campaign 3"]: operation = client.get_type("CampaignOperation") operation.create.name = campaign_name operations.append(operation) # Mutate with multiple operations request = client.get_type("MutateCampaignsRequest") request.customer_id = customer_id request.operations = operations response = service.mutate_campaigns(request=request) # Iterate over responses for result in response.results: print(f"Created campaign: {result.resource_name}") ``` -------------------------------- ### load_from_dict Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/google-ads-client.md Creates a GoogleAdsClient instance from a configuration dictionary. This is a convenient way to initialize the client when your configuration is already in a dictionary format. ```APIDOC ## `load_from_dict` ### Description Create a GoogleAdsClient from a configuration dictionary. ### Method Signature ```python @classmethod load_from_dict( config_dict: Dict[str, Any], version: Union[str, None] = None ) -> GoogleAdsClient ``` ### Parameters #### Path Parameters * **config_dict** (Dict[str, Any]) - Required - Configuration dictionary * **version** (Union[str, None]) - Optional - API version to use ### Returns A configured `GoogleAdsClient` instance. ### Raises * `ValueError` — If the dictionary is invalid or missing required keys ### Example ```python config = { "developer_token": "xxx...", "client_id": "xxx...", "client_secret": "xxx...", "refresh_token": "xxx...", "use_proto_plus": False, } client = GoogleAdsClient.load_from_dict(config) ``` ``` -------------------------------- ### Composing Messages with Nested Fields Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/types-and-messages.md Messages can contain other messages and lists. This example demonstrates setting nested fields like `campaign_budget` and operations within a `CampaignOperation`. ```python # Campaign contains CampaignBudget campaign = client.get_type("Campaign") campaign_budget = client.get_type("CampaignBudget") campaign.campaign_budget = campaign_budget # Operations contain messages campaign_operation = client.get_type("CampaignOperation") campaign_operation.create = client.get_type("Campaign") campaign_operation.update = client.get_type("Campaign") campaign_operation.remove = campaign_resource_name # Responses contain lists of resources search_response = client.get_type("SearchGoogleAdsResponse") # Contains: search_response.results (list of GoogleAdsRow) # Each row contains: customer, campaign, ad_group, ad, keyword, etc. ``` -------------------------------- ### Basic Error Catching Example Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/errors.md Demonstrates how to catch a GoogleAdsException during an API call and print basic error information like the request ID and error message. ```python from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException try: client = GoogleAdsClient.load_from_storage() service = client.get_service("CampaignService") campaign = service.get_campaign( customer_id="1234567890", resource_name="customers/1234567890/campaigns/999999999" # Invalid ID ) except GoogleAdsException as ex: print(f"Request ID: {ex.request_id}") print(f"Error code: {ex.error.code()}") print(f"Error message: {ex.error.details()}") ``` -------------------------------- ### Create Assets Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Creates text and image assets. Image assets require binary data. Requires the AssetService. ```python # Create text asset text_asset = client.get_type("Asset") text_asset.text_asset.text = "Best Product Ever" # Create image asset (requires image URL) image_asset = client.get_type("Asset") image_asset.image_asset.data = open("image.png", "rb").read() service = client.get_service("AssetService") for asset_type in [text_asset, image_asset]: operation = client.get_type("AssetOperation") operation.create = asset_type response = service.mutate_assets( customer_id="1234567890", operations=[operation] ) print(f"Created asset: {response.results[0].resource_name}") ``` -------------------------------- ### Load Google Ads Client for Different Environments Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/advanced-patterns.md Loads the Google Ads client configuration based on the specified environment (development, staging, production). Uses different YAML files for each environment. ```python import os from google.ads.googleads.client import GoogleAdsClient class ConfigManager: @staticmethod def get_client_for_environment(env="production"): """Load client for specific environment.""" env_map = { "development": "google-ads-dev.yaml", "staging": "google-ads-staging.yaml", "production": "google-ads.yaml", } config_file = env_map.get(env, "google-ads.yaml") return GoogleAdsClient.load_from_storage(path=config_file) # Usage dev_client = ConfigManager.get_client_for_environment("development") prod_client = ConfigManager.get_client_for_environment("production") ``` -------------------------------- ### Load Configuration from YAML File Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/configuration.md Loads configuration from a YAML file. If no path is provided, it checks environment variables or defaults to a standard location. ```python from google.ads.googleads import config # Load from default location cfg = config.load_from_yaml_file() # Load from custom path cfg = config.load_from_yaml_file("/etc/google-ads.yaml") ``` -------------------------------- ### Setting Enum Values Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/types-and-messages.md Enum values can be set directly using the client's `enums` attribute. This example shows setting the status for different resource types. ```python campaign.status = client.enums.CampaignStatus.PAUSED ad_group.status = client.enums.AdGroupStatus.ENABLED ad.status = client.enums.AdStatus.ENABLED keyword.match_type = client.enums.KeywordMatchType.BROAD bid_modifier.device = client.enums.DeviceType.MOBILE budget.period = client.enums.BudgetPeriod.DAILY strategy.type = client.enums.BiddingStrategyType.MANUAL_CPC ``` -------------------------------- ### Create and Use a Custom gRPC Interceptor Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/api-reference/interceptors.md Demonstrates how to create a custom gRPC interceptor and pass it when retrieving a service client. This allows for custom request/response handling. ```python from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.interceptors import Interceptor import grpc # Create a custom interceptor class CustomInterceptor(grpc.UnaryUnaryClientInterceptor): def intercept_unary_unary(self, continuation, client_call_details, request ): # Your custom logic here return continuation(client_call_details, request) client = GoogleAdsClient.load_from_storage() service = client.get_service( "CampaignService", interceptors=[CustomInterceptor()] ) ``` -------------------------------- ### SEARCH Operation: Querying Resources Source: https://github.com/googleads/google-ads-python/blob/main/_autodocs/services-reference.md Shows how to use the SEARCH method with Google Ads Query Language (GAQL) to find resources that match specified criteria. This is useful for retrieving lists of resources. ```python service = client.get_service("GoogleAdsService") # Search for resources matching criteria response = service.search( customer_id="1234567890", query="SELECT campaign.id, campaign.name FROM campaign" ) for row in response.results: print(f"Campaign: {row.campaign.name}") ```