What you’ll learn: Variables, functions, loops, working with CSVs and JSON, DataFrames with pandas, and how to read/write Google Sheets—everything you need to automate marketing tasks. Zero programming experience assumed.
| API | Get Access | Key Format | Env Variable |
|---|---|---|---|
| Anthropic Claude | console.anthropic.com | sk-ant-api... | ANTHROPIC_API_KEY |
| OpenAI GPT | platform.openai.com | sk-... | OPENAI_API_KEY |
| Google Gemini | aistudio.google.com | AIza... | GOOGLE_API_KEY |
| Google Ads | ads.google.com > API Center | Developer token + OAuth 2.0 | GOOGLE_ADS_DEVELOPER_TOKEN |
| Meta Marketing | developers.facebook.com | Access token (OAuth) | META_ACCESS_TOKEN |
| Amazon Ads | advertising.amazon.com | Client ID + OAuth | AMAZON_CLIENT_ID |
| SearchAPI | searchapi.io | API key string | SEARCHAPI_KEY |
| GA4 Data API | console.cloud.google.com | Service account JSON | GOOGLE_APPLICATION_CREDENTIALS |
| Google Sheets | console.cloud.google.com | Service account JSON | (same as above) |
Python is the most popular programming language for data analysis and AI. It is also the easiest to learn. If you can write a Google Ads query in the platform’s interface, you can learn Python. The syntax reads like English: ‘for each campaign in campaigns: print the name’ is almost exactly how you write it in Python.
Variables and Data Types
# Variables store data
campaign_name = 'Brand Search' # String (text)
daily_budget = 150.00 # Float (decimal number)
clicks = 1234 # Integer (whole number)
is_active = True # Boolean (True/False)
# Lists store multiple items
keywords = ['running shoes', 'marathon gear', 'trail shoes']
cpas = [12.50, 18.30, 9.75, 22.10]
# Dictionaries store key-value pairs (like a spreadsheet row)
campaign = {
'name': 'Brand Search',
'budget': 150.00,
'clicks': 1234,
'conversions': 89,
'cpa': 13.87
}
print(f'Campaign: {campaign["name"]} | CPA: ${campaign["cpa"]}')
Functions: Reusable Calculations
def calculate_roas(revenue, cost):
'''Calculate Return on Ad Spend.'''
if cost == 0:
return 0
return revenue / cost
def is_profitable(campaign, target_roas=3.0):
'''Check if a campaign meets ROAS target.'''
roas = calculate_roas(campaign['revenue'], campaign['cost'])
return roas >= target_roas
# Use it:
camp = {'name': 'Shopping', 'revenue': 45000, 'cost': 12000}
roas = calculate_roas(camp['revenue'], camp['cost'])
print(f'{camp["name"]}: ROAS = {roas:.2f}x') # Shopping: ROAS = 3.75x
Loops: Process Data at Scale
campaigns = [
{'name':'Brand','cost':5000,'conversions':400,'revenue':20000},
{'name':'Non-Brand','cost':15000,'conversions':200,'revenue':35000},
{'name':'Shopping','cost':8000,'conversions':150,'revenue':18000},
{'name':'PMax','cost':12000,'conversions':180,'revenue':28000},
]
# Analyze every campaign automatically
for camp in campaigns:
cpa = camp['cost'] / camp['conversions'] if camp['conversions'] > 0 else 0
roas = camp['revenue'] / camp['cost'] if camp['cost'] > 0 else 0
status = 'PROFITABLE' if roas > 2.0 else 'REVIEW'
print(f'{camp["name"]:12} | CPA: ${cpa:7.2f} | ROAS: {roas:.2f}x | {status}')
Pandas: DataFrames for Marketing Data
import pandas as pd
# Read a CSV exported from Google Ads
df = pd.read_csv('campaign_report.csv')
# Quick analysis
print(df.describe()) # Summary stats for all columns
print(df.groupby('Campaign')['Cost'].sum()) # Total cost per campaign
# Filter for unprofitable campaigns
wasteful = df[(df['Conversions'] == 0) & (df['Cost'] > 50)]
print(f'Found {len(wasteful)} queries wasting money')
# Export results
wasteful.to_csv('wasteful_queries.csv', index=False)
Working with Google Sheets
import gspread
from google.oauth2.service_account import Credentials
# Setup (one-time): Create service account in Google Cloud Console
# Download JSON key, share your Sheet with the service account email
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = Credentials.from_service_account_file('creds.json', scopes=scopes)
gc = gspread.authorize(creds)
# Read data from a sheet
sheet = gc.open('Campaign Data').sheet1
data = sheet.get_all_records() # Returns list of dictionaries
# Write results back
sheet.update('G1', [['AI Analysis']]) # Header
for i, row in enumerate(data):
analysis = f'CPA ${row["Cost"]/max(row["Conversions"],1):.2f}'
sheet.update(f'G{i+2}', [[analysis]])
The Python scripts powering GoogleAdsAgent.ai use exactly these patterns: dictionaries for campaign data, functions for calculations, loops for batch processing, pandas for analysis, and gspread for Google Sheets integration. Understanding these fundamentals means you can read, modify, and extend every tool in the open-source library.
📦 GitHub: https://github.com/itallstartedwithaidea/google-ads-api-agent — See /actions/ folder for production Python using all patterns above
Website: googleadsagent.ai | GitHub: https://github.com/itallstartedwithaidea | Tools: googleadsagent.ai/tools
John Williams | Senior Paid Media Specialist, Seer Interactive | $48M+ managed spend | Creator, GoogleAdsAgent.ai | Hero Conf Speaker | github.com/itallstartedwithaidea
Get a free 30-day audit of your advertising accounts. John will personally review your setup and provide actionable recommendations.
John will review your account and reach out within 24 hours.