CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-ads

Client library for the Google Ads API providing comprehensive access to advertising management, reporting, and analytics capabilities.

Pending
Overview
Eval results
Files

client-setup.mddocs/

Client Setup and Authentication

Core client initialization, configuration management, and authentication flows for the Google Ads Python client library. This includes OAuth2 flows, service account authentication, and various client configuration methods.

Capabilities

Client Initialization

The GoogleAdsClient provides multiple methods for initialization with different configuration sources.

class GoogleAdsClient:
    """Google Ads client used to configure settings and fetch services."""
    
    def __init__(
        self,
        credentials,
        developer_token: str,
        endpoint: str = None,
        login_customer_id: str = None,
        logging_config: dict = None,
        linked_customer_id: str = None,
        version: str = None,
        http_proxy: str = None,
        use_proto_plus: bool = False,
        use_cloud_org_for_api_access: str = None
    ):
        """
        Initialize GoogleAdsClient with credentials and configuration.
        
        Parameters:
        - credentials: Google OAuth2 credentials instance
        - developer_token: Google Ads developer token
        - endpoint: Optional alternative API endpoint
        - login_customer_id: Login customer ID for API access
        - logging_config: Dictionary with logging configuration
        - linked_customer_id: Linked customer ID for API access
        - version: API version to use (v19, v20, v21)
        - http_proxy: Proxy URI for connections
        - use_proto_plus: Use proto-plus message interfaces
        - use_cloud_org_for_api_access: Use cloud org for access levels
        """
    
    @classmethod
    def load_from_storage(cls, path: str = None, version: str = None) -> 'GoogleAdsClient':
        """
        Create client from YAML configuration file.
        
        Parameters:
        - path: Path to YAML file (defaults to google-ads.yaml)
        - version: API version to use
        
        Returns:
        GoogleAdsClient initialized from file
        
        Raises:
        - FileNotFoundError: If configuration file doesn't exist
        - ValueError: If configuration lacks required fields
        """
    
    @classmethod
    def load_from_env(cls, version: str = None) -> 'GoogleAdsClient':
        """
        Create client from environment variables.
        
        Parameters:
        - version: API version to use
        
        Returns:
        GoogleAdsClient initialized from environment
        
        Raises:
        - ValueError: If environment lacks required variables
        """
    
    @classmethod
    def load_from_dict(cls, config_dict: dict, version: str = None) -> 'GoogleAdsClient':
        """
        Create client from configuration dictionary.
        
        Parameters:
        - config_dict: Dictionary with configuration data
        - version: API version to use
        
        Returns:
        GoogleAdsClient initialized from dictionary
        
        Raises:
        - ValueError: If dictionary lacks required fields
        """
    
    @classmethod 
    def load_from_string(cls, yaml_str: str, version: str = None) -> 'GoogleAdsClient':
        """
        Create client from YAML string.
        
        Parameters:
        - yaml_str: YAML configuration as string
        - version: API version to use
        
        Returns:
        GoogleAdsClient initialized from YAML string
        
        Raises:
        - ValueError: If YAML lacks required fields
        """

Service Access

Access to Google Ads API services through the client.

def get_service(self, name: str, version: str = None, interceptors: list = None) -> object:
    """
    Get a service client instance for the specified service.
    
    Parameters:
    - name: Service name (e.g., "CampaignService", "GoogleAdsService")
    - version: API version override (v19, v20, v21)
    - interceptors: Optional list of custom interceptors
    
    Returns:
    Service client instance for the specified service
    
    Raises:
    - ValueError: If service doesn't exist in specified version
    """

Configuration Management

Configuration loading and validation utilities.

# Configuration functions
def load_from_env() -> dict:
    """
    Load configuration from environment variables.
    
    Returns:
    Dictionary with configuration from environment variables
    
    Environment Variables:
    - GOOGLE_ADS_DEVELOPER_TOKEN: Required developer token
    - GOOGLE_ADS_CLIENT_ID: OAuth2 client ID
    - GOOGLE_ADS_CLIENT_SECRET: OAuth2 client secret
    - GOOGLE_ADS_REFRESH_TOKEN: OAuth2 refresh token
    - GOOGLE_ADS_LOGIN_CUSTOMER_ID: Optional login customer ID
    """

def load_from_yaml_file(path: str = None) -> dict:
    """
    Load configuration from YAML file.
    
    Parameters:
    - path: Path to YAML file (defaults to ./google-ads.yaml)
    
    Returns:
    Dictionary with configuration from YAML file
    
    Raises:
    - FileNotFoundError: If file doesn't exist
    - IOError: If file can't be read
    """

def load_from_dict(config_dict: dict) -> dict:
    """
    Load configuration from dictionary with validation.
    
    Parameters:
    - config_dict: Configuration dictionary
    
    Returns:
    Validated configuration dictionary
    
    Raises:
    - ValueError: If required keys are missing
    """

def parse_yaml_document_to_dict(yaml_str: str) -> dict:
    """
    Parse YAML string to configuration dictionary.
    
    Parameters:
    - yaml_str: YAML configuration string
    
    Returns:
    Configuration dictionary
    
    Raises:
    - ValueError: If YAML is invalid
    """

OAuth2 Authentication

OAuth2 credential management for different authentication flows.

# OAuth2 functions
def get_credentials(config_data: dict) -> object:
    """
    Get OAuth2 credentials from configuration data.
    
    Parameters:
    - config_data: Configuration dictionary
    
    Returns:
    Google OAuth2 credentials object
    
    Raises:
    - ValueError: If required authentication fields are missing
    """

def get_installed_app_credentials(
    client_id: str,
    client_secret: str,
    refresh_token: str,
    http_proxy: str = None,
    token_uri: str = None
) -> object:
    """
    Get credentials using installed application OAuth2 flow.
    
    Parameters:
    - client_id: OAuth2 client_id from configuration
    - client_secret: OAuth2 client_secret from configuration  
    - refresh_token: OAuth2 refresh_token from configuration
    - http_proxy: Optional HTTP proxy URI
    - token_uri: Optional custom token URI
    
    Returns:
    OAuth2 credentials for installed app flow
    """

def get_service_account_credentials(
    json_key_file_path: str,
    subject: str,
    http_proxy: str = None,
    scopes: list = None
) -> object:
    """
    Get credentials using service account authentication.
    
    Parameters:
    - json_key_file_path: Path to the private key file
    - subject: Email address of the delegated account
    - http_proxy: Optional HTTP proxy URI
    - scopes: List of additional scopes
    
    Returns:
    OAuth2 credentials for service account flow
    """

Usage Examples

Basic Client Setup from YAML

from google.ads.googleads.client import GoogleAdsClient

# Create google-ads.yaml file with configuration
yaml_content = """
developer_token: "your_developer_token_here"
client_id: "your_client_id_here.apps.googleusercontent.com"
client_secret: "your_client_secret_here"
refresh_token: "your_refresh_token_here"
login_customer_id: "1234567890"
"""

# Initialize client
client = GoogleAdsClient.load_from_storage("google-ads.yaml")

# Access services
campaign_service = client.get_service("CampaignService")
googleads_service = client.get_service("GoogleAdsService")

Environment Variable Setup

import os
from google.ads.googleads.client import GoogleAdsClient

# Set environment variables
os.environ['GOOGLE_ADS_DEVELOPER_TOKEN'] = 'your_developer_token'
os.environ['GOOGLE_ADS_CLIENT_ID'] = 'your_client_id.apps.googleusercontent.com'
os.environ['GOOGLE_ADS_CLIENT_SECRET'] = 'your_client_secret'
os.environ['GOOGLE_ADS_REFRESH_TOKEN'] = 'your_refresh_token'
os.environ['GOOGLE_ADS_LOGIN_CUSTOMER_ID'] = '1234567890'

# Initialize client from environment
client = GoogleAdsClient.load_from_env()

Service Account Authentication

from google.ads.googleads.client import GoogleAdsClient

# Configuration with service account
config = {
    'developer_token': 'your_developer_token',
    'service_account_key_file': '/path/to/service-account.json',
    'login_customer_id': '1234567890'
}

client = GoogleAdsClient.load_from_dict(config)

Custom Client Initialization

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads import oauth2

# Manual credential setup
credentials = oauth2.get_installed_app_credentials(
    client_id='your_client_id.apps.googleusercontent.com',
    client_secret='your_client_secret',
    refresh_token='your_refresh_token'
)

# Initialize with custom settings
client = GoogleAdsClient(
    credentials=credentials,
    developer_token='your_developer_token',
    login_customer_id='1234567890',
    version='v21',
    use_proto_plus=True
)

Configuration Keys

Required Keys

REQUIRED_KEYS = {
    'developer_token',  # Google Ads developer token
}

# OAuth2 Installed App Flow
REQUIRED_INSTALLED_APP_KEYS = {
    'client_id',        # OAuth2 client ID
    'client_secret',    # OAuth2 client secret  
    'refresh_token'     # OAuth2 refresh token
}

# Service Account Flow
REQUIRED_SERVICE_ACCOUNT_KEYS = {
    'service_account_key_file',  # Path to service account JSON
    # OR
    'service_account_key_data'   # Service account JSON as string
}

Optional Keys

OPTIONAL_KEYS = {
    'login_customer_id',                    # Login customer ID
    'linked_customer_id',                   # Linked customer ID
    'endpoint',                             # Alternative API endpoint
    'http_proxy',                           # HTTP proxy URI
    'use_proto_plus',                       # Use proto-plus messages
    'use_cloud_org_for_api_access',         # Use cloud org access
    'logging'                               # Logging configuration
}

Constants

# OAuth2 scope for Google Ads API
GOOGLE_ADS_SCOPE = "https://www.googleapis.com/auth/adwords"

# Valid API versions
VALID_API_VERSIONS = ["v21", "v20", "v19"]

# Default API version
DEFAULT_VERSION = "v21"

Install with Tessl CLI

npx tessl i tessl/pypi-google-ads

docs

ad-management.md

asset-management.md

audience-management.md

batch-operations.md

campaign-management.md

client-setup.md

conversion-tracking.md

index.md

reporting-search.md

targeting-keywords.md

tile.json