Date: 2026-07-07
The Problem
Google Analytics is a dashboard you click through. You log in, navigate to reports, filter by organic traffic, export CSVs, manually compare last month to this month. It takes 10 minutes to answer one question. Across 12 properties, that’s an hour of clicking.
Meanwhile, AI is sitting there with zero context about your traffic. Every conversation starts blank. “What’s my organic traffic?” — you have to go look, come back, paste numbers.
The real problem: **GA4 has an API, but nobody bridges it to AI workflows.**
The Solution
A Python middleman script that:
1. Authenticates via OAuth once (opens browser, you sign in, saves refresh token)
2. Discovers all your GA4 properties automatically via Admin API
3. Queries the Data API for organic traffic, landing pages, source/medium, engagement metrics
4. Returns structured, readable output that AI can parse and act on
Then AI reads the output and says: “Gridfinity generator has 126 Bing sessions but zero Google — verify Search Console indexing.” Not “click here, then here, then export this.”
Architecture
┌──────────────┐ OAuth ┌───────────────┐ REST API ┌──────────────────┐
│ Google Cloud │ ◄────────────► │ Python Script │ ◄────────────► │ GA4 Data API │
│ OAuth Client │ refresh │ (ga4_seo.py) │ runReport │ properties/* │
└──────────────┘ token └───────┬───────┘ └──────────────────┘
│
│ structured text output
▼
┌──────────────┐
│ AI Assistant │
│ reads report │
│ writes todos │
└──────────────┘
The AI never touches GA4. It only reads the script’s output. The script handles auth, pagination, filtering, and Unicode sanitization (Windows terminals hate emojis in landing page URLs).
Key Design Decisions
**Why Python, not a GA4 dashboard?**
Python gives AI programmatic access. A dashboard gives you a chart. The AI can’t read a chart — it reads text. This script outputs exactly what an AI needs: property list, session counts, bounce rates, top pages, and deltas from last check.
**Why OAuth, not a service account?**
Service accounts need domain-wide delegation for GA4 — overkill for a personal portfolio. OAuth with a Desktop app client ID is 3 clicks: download JSON, run script, sign in once.
**Why discover properties via API, not manual entry?**
I had 12 properties spread across 2 accounts. Manually typing IDs guarantees errors. The Admin API’s `listAccountSummaries` returns everything in one call — then you pick which ones to monitor.
The Script in Action
First run — auth and discover
python ga4_seo.py auth # Opens browser, Google sign-in, saves token
python ga4_seo.py discover # Lists all 12 properties automatically
python ga4_seo.py save-discovered # Caches them locally
Output:
ACCOUNT | PROPERTY ID | DISPLAY NAME
----------------+--------------+-------------------------
jcianci12 | 320854240 | TekOnline
jcianci12 | 527960020 | auction fast view
jcianci12 | 539926641 | gridfinity generator
...
Total: 12 properties across 2 accounts
Ongoing — AI reads report, writes tasks
python ga4_seo.py report # Organic traffic for all 12 properties
python ga4_seo.py pages # Top organic landing pages per property
AI sees:
PROPERTY: gridfinity generator (539926641)
Sessions : 126
Users : 114
Avg Bounce : 0.2%
Source: 100% Bing. Zero Google.
AI responds:
> Gridfinity still zero Google. Search Console sitemap submitted but not indexed yet. Request Indexing on the homepage URL.
Then AI writes a todo item into `gridfinity generator/todo.md`. No human had to open GA4, find the right property, or trace the issue.
The Full Pipeline
| Step | Who does it | Time |
| Discover properties | Script (API) | 2 seconds |
| Query organic traffic | Script (API) | 15 seconds (12 properties) |
| Compare to last check | AI reads both outputs | Instant |
| Identify problems | AI flags anomalies | Instant |
| Write action items | AI edits project todos | 5 seconds |
| Human acts | You click Search Console | 2 minutes |
| Verify fix | Re-run script next day | 15 seconds |
Total time to know what’s wrong across 12 properties: **20 seconds**. Without this: 30-60 minutes of manual GA4 clicking.
What You Need to Set This Up
Requirements
– Python 3.9+
– `pip install google-analytics-data google-analytics-admin google-auth-oauthlib`
– A Google Cloud project with Analytics Data API and Analytics Admin API enabled
– An OAuth 2.0 Desktop client ID (download as `client_secrets.json`)
Getting the OAuth client
1. Go to [Google Cloud Console](https://console.cloud.google.com/apis/credentials)
2. Create project → enable “Google Analytics Data API” and “Google Analytics Admin API”
3. Credentials → Create OAuth Client ID → Application type: “Desktop app”
4. Download JSON → rename to `client_secrets.json`
Running it
git clone https://github.com/jcianci/ga4-seo-middleman # or wherever you host it
cd ga4-seo-middleman
pip install -r requirements.txt
python ga4_seo.py auth # One-time OAuth
python ga4_seo.py report # Daily SEO check
Daily AI workflow
You: "Check my analytics"
AI: [runs python ga4_seo.py report in background]
AI: reads output → "3 properties have traffic. Gridfinity +18 sessions but still zero Google.
Auction fast view up 34% — /dashboard jumped 19 sessions. Checked and wrote todo items."
You: "Fix the gridfinity issue"
AI: [opens Search Console, requests indexing, updates todo.md as done]
Real Results
After 3 weeks of running this pipeline across my SEO portfolio:
| Property | Monthly Sessions | Trend | AI Action Taken |
| TekOnline (blog) | 476 | Stable | Flagged 58 untracked pages, recommended GA4 tag audit |
| Gridfinity Generator | 126 | +17% | Discovered zero Google indexing, wrote GSC verification steps |
| Auction FastView | 78 | +34% | Confirmed tracking healthy, recommended sitemap submission |
| WeHireIt | 1 | First hit | Noted as new signal |
The AI doesn’t just report numbers — it **writes todo items into project files**. That’s the difference between a dashboard and an automated decision-making pipeline.
Limitations
– **GA4 data has 24-48 hour lag.** The API always returns yesterday’s data at best. You won’t get real-time numbers.
– **OAuth tokens expire.** Refresh tokens can be revoked by Google after 6 months for apps in testing mode. The script auto-deletes expired tokens and prompts re-auth.
– **Search Console data needs a separate API.** The script attempts `googleOrganicQuery` dimension via GA4, but it only works if Search Console is linked to the GA4 property. Real query data needs the Search Console API.
– **Not a replacement for GA4.** You still need GA4 for deep dives, segment comparisons, and exploration. This is for daily health checks and AI-driven triage.
Source Code
The full script is at `C:\Users\jcian\OneDrive\Desktop\IT\ga4-middleman\ga4_seo.py`. It’s self-contained — no framework, no database, no config files beyond `client_secrets.json` and the cached token.
Key functions:
– `get_credentials()` — OAuth with auto-refresh, fallback to browser re-auth
– `discover_properties()` — Admin API `listAccountSummaries`
– `run_seo_report()` — Data API `runReport` with organic source/medium filter
– `run_landing_pages()` — Top 20 organic landing pages by session count
Commands:
– `auth` — OAuth dance
– `discover` / `save-discovered` — auto-find and cache properties
– `report [days]` — organic traffic by property
– `pages [days]` — top landing pages
– `query [days]` — Search Console query data (if linked)
– `add
– `list` — show cached properties
Leave a Reply