How to Use the Google Ads API: A Practical Guide with Code Examples
Google Ads is a powerful platform for driving traffic and generating leads, but managing campaigns manually can be time-consuming. That’s where the Google Ads API comes in—offering automation, scalability, and deeper insights into your ad performance. In this guide, we’ll walk you through the basics of using the Google Ads API with practical code examples to help you streamline your advertising efforts.
Getting Started with the Google Ads API
Before diving into the code, you’ll need to set up your Google Ads API credentials. Here’s a quick rundown:
-
Create a Google Cloud Project: Go to the Google Cloud Console, create a new project, and enable the Google Ads API.
-
Create OAuth2 Credentials: Set up OAuth2 credentials to authenticate your application. You’ll need to download the client secret JSON file.
-
Link Your Google Ads Account: Link your Google Ads account to your Google Cloud project to gain access.
-
Install the Google Ads API Client Library: You can use different programming languages, but in this example, we’ll use Python. Install the client library by running:
pip install google-ads
Example 1: Retrieving Campaigns
Once your setup is complete, you can start retrieving data from your Google Ads account. The following Python script retrieves a list of active campaigns:
from google.ads.google_ads.client import GoogleAdsClient
# Load your Google Ads client credentials
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")
# Define customer ID (replace with your Google Ads account ID)
customer_id = "INSERT_CUSTOMER_ID_HERE"
def get_campaigns(client, customer_id):
query = """
SELECT
campaign.id,
campaign.name,
campaign.status
FROM campaign
WHERE campaign.status = 'ENABLED'
"""
ga_service = client.get_service("GoogleAdsService")
response = ga_service.search(customer_id=customer_id, query=query)
for row in response:
print(f"Campaign ID: {row.campaign.id}, Name: {row.campaign.name}, Status: {row.campaign.status}")
get_campaigns(client, customer_id)
This script connects to the Google Ads API, runs a query to fetch all active campaigns, and prints their IDs, names, and statuses.
Example 2: Adding Keywords to a Campaign
Let’s add new keywords to an existing campaign. This is especially useful when scaling your campaigns with fresh keyword ideas generated by our solution:
python
from google.ads.google_ads.errors import GoogleAdsException
from google.ads.google_ads.v11.services.types import AdGroupCriterionOperation
def add_keywords(client, customer_id, ad_group_id, keywords):
ad_group_criterion_service = client.get_service("AdGroupCriterionService")
# Create operations to add keywords
operations = []
for keyword in keywords:
operation = AdGroupCriterionOperation()
ad_group_criterion = operation.create
ad_group_criterion.ad_group = client.get_service("ResourceName").format("customers/{}/adGroups/{}", customer_id, ad_group_id)
ad_group_criterion.status = client.enums.AdGroupCriterionStatusEnum.ENABLED
ad_group_criterion.keyword.text = keyword
ad_group_criterion.keyword.match_type = client.enums.KeywordMatchTypeEnum.EXACT
operations.append(operation)
# Send the request
try:
response = ad_group_criterion_service.mutate_ad_group_criteria(customer_id=customer_id, operations=operations)
print(f"Added keywords: {[keyword for keyword in keywords]}")
except GoogleAdsException as ex:
print(f"Failed to add keywords: {ex}")
# Example usage
ad_group_id = "INSERT_AD_GROUP_ID_HERE"
keywords = ["example keyword 1", "example keyword 2"]
add_keywords(client, customer_id, ad_group_id, keywords)
This code snippet allows you to add a list of keywords to a specified ad group within your Google Ads account. The keywords are set to exact match type, but you can adjust this based on your campaign strategy.
Example 3: Pausing an Ad Group
Managing ad groups is essential for controlling your budget and targeting. Here’s how you can pause an ad group using the API:
from google.ads.google_ads.v11.services.types import AdGroupOperation
def pause_ad_group(client, customer_id, ad_group_id):
ad_group_service = client.get_service("AdGroupService")
ad_group_operation = AdGroupOperation()
ad_group = ad_group_operation.update
ad_group.resource_name = ad_group_service.ad_group_path(customer_id, ad_group_id)
ad_group.status = client.enums.AdGroupStatusEnum.PAUSED
# Set the update mask
client.copy_from(ad_group_operation.update_mask, {"paths": ["status"]})
response = ad_group_service.mutate_ad_groups(customer_id=customer_id, operations=[ad_group_operation])
print(f"Ad Group ID {ad_group_id} has been paused.")
# Example usage
pause_ad_group(client, customer_id, ad_group_id)
This script pauses a specific ad group, allowing you to easily manage your campaigns and pause underperforming ad groups without manual intervention.
Conclusion
The Google Ads API opens up a world of possibilities for automating your ad campaigns, saving you time and optimizing performance. With practical use cases like retrieving campaigns, adding keywords, and managing ad groups, you can streamline your Google Ads management and focus more on strategic growth.
Try integrating these examples into your workflow, and see how the Google Ads API can enhance your advertising strategy!