Google Ads Python Client Library

30.0.0 · active · verified Sun Mar 29

The `google-ads` Python client library provides a robust interface for interacting with the Google Ads API. It simplifies credential management and the creation of API service clients, enabling programmatic access to Google Ads features. The library maintains an active development status with frequent releases, often synchronized with new Google Ads API versions, currently at 30.0.0 and requiring Python 3.9 or higher.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Google Ads client and perform a simple API request to list campaigns. It assumes authentication details are configured via a `google-ads.yaml` file (by default in the user's home directory) or environment variables. Replace `GOOGLE_ADS_CUSTOMER_ID` with an actual customer ID to run.

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

# Ensure your google-ads.yaml is configured or environment variables are set.
# For quickstart, we assume a google-ads.yaml in the home directory or specified path.
# You would typically set client_id, client_secret, refresh_token, developer_token,
# and login_customer_id in this file or via environment variables.
# Example: os.environ['GOOGLE_ADS_DEVELOPER_TOKEN'] = 'YOUR_DEVELOPER_TOKEN'
# For full authentication setup, refer to Google Ads API documentation.

# Initialize the client. By default, it loads from google-ads.yaml in your home directory.
# Or specify path: GoogleAdsClient.load_from_storage(path='path/to/google-ads.yaml')
try:
    client = GoogleAdsClient.load_from_storage()
except Exception as e:
    print(f"Failed to load Google Ads client configuration: {e}")
    print("Please ensure your google-ads.yaml file is correctly configured or credentials are set via environment variables.")
    exit(1)

# Replace with your Google Ads customer ID
# If using a manager account, this is the ID of the account you want to query.
customer_id = os.environ.get('GOOGLE_ADS_CUSTOMER_ID', '123-456-7890').replace('-', '') # Remove hyphens

def main(client, customer_id):
    try:
        ga_service = client.get_service("GoogleAdsService")

        # Create a query to select all active campaigns
        query = """
            SELECT
                campaign.id,
                campaign.name,
                campaign.status
            FROM
                campaign
            ORDER BY
                campaign.id
            """

        # Issue a search request.
        response = ga_service.search(customer_id=customer_id, query=query)

        print(f"Listing campaigns for customer ID: {customer_id}")
        for row in response:
            campaign = row.campaign
            print(f"\tCampaign ID: {campaign.id}, Name: {campaign.name}, Status: {campaign.status.name}")

    except Exception as e:
        print(f"An API error occurred: {e}")

if __name__ == "__main__":
    main(client, customer_id)

view raw JSON →