Google Analytics 4
Query GA4 properties directly via the Google Analytics Data API (analyticsdata.googleapis.com).
Setup (one-time)
1. Create a Google Cloud project (or use an existing one)
Go to https://console.cloud.google.com and create or select a project.
2. Set the OAuth consent screen to Internal
Go to APIs & Credentials > OAuth consent screen > Audience and set:
This avoids Google's app verification process (which requires a demo video for sensitive scopes like Analytics). Internal is fine for personal/team use. Note: this requires a Google Workspace account (not a personal @gmail.com).
If you must use External (e.g. you have a personal Gmail), set publishing status to "In production" and add the analytics.readonly scope under Data Access / Scopes.
3. Add the Analytics scope
Go to OAuth consent screen > Data Access (or Scopes) and add:
https://www.googleapis.com/auth/analytics.readonly
This is listed as a "sensitive scope" by Google. If your app is Internal, no verification is needed.
4. Enable the Analytics Data API
Go to: https://console.cloud.google.com/apis/library/analyticsdata.googleapis.com
Click Enable.
5. Create OAuth 2.0 credentials
Go to APIs & Credentials > Credentials > Create Credentials > OAuth client ID
- - Application type: Desktop app
- Name: anything you want
Save the Client ID and Client Secret.
6. Get your GA4 Property ID
Go to https://analytics.google.com > Admin (gear icon) > Property Settings. The Property ID is the numeric value at the top.
7. Generate a refresh token
Run this on your local machine (needs a browser for the Google login flow):
CODEBLOCK1
CODEBLOCK2
Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your values. A browser window will open for you to log in with Google. Copy the refresh token from the output.
8. Set environment variables
CODEBLOCK3
Troubleshooting
- - 403 HTML error page: The
analytics.readonly scope is probably not added to your OAuth consent screen. Go to Data Access/Scopes and add it, then regenerate your refresh token. - 403 JSON error "caller does not have permission": Your Google account doesn't have access to the GA4 property. Check Admin > Property Access Management in Google Analytics.
- Token refresh fails: Your refresh token may be expired. Regenerate it using step 7.
Queries
Top pages by pageviews
CODEBLOCK4
Top pages with sessions and users
CODEBLOCK5
Traffic sources
CODEBLOCK6
Traffic by source and medium
CODEBLOCK7
Landing pages
CODEBLOCK8
Custom date range
CODEBLOCK9
Filter by path prefix
CODEBLOCK10
Conversions by campaign
CODEBLOCK11
Device breakdown
CODEBLOCK12
Country breakdown
CODEBLOCK13
Common metrics
screenPageViews,
sessions,
totalUsers,
newUsers,
activeUsers,
bounceRate,
averageSessionDuration,
conversions,
eventCount,
engagementRate, INLINECODE15
Common dimensions
pagePath,
pageTitle,
landingPage,
sessionSource,
sessionMedium,
sessionCampaignName,
country,
city,
deviceCategory,
browser,
date,
week, INLINECODE28
Output
Results are printed as a formatted table to stdout. Pipe to
| python3 -m json.tool if you need raw JSON.
Google Analytics 4
通过 Google Analytics Data API(analyticsdata.googleapis.com)直接查询 GA4 媒体资源。
设置(一次性操作)
1. 创建 Google Cloud 项目(或使用现有项目)
访问 https://console.cloud.google.com 创建或选择一个项目。
2. 将 OAuth 同意屏幕设置为内部
进入 API 和服务 > OAuth 同意屏幕 > 受众群体,设置:
这样可以避免 Google 的应用验证流程(对于 Analytics 等敏感范围,该流程需要演示视频)。内部模式适用于个人/团队使用。注意:这需要 Google Workspace 账号(而非个人 @gmail.com 账号)。
如果必须使用外部模式(例如您使用的是个人 Gmail),请将发布状态设置为正式版,并在数据访问/范围下添加 analytics.readonly 范围。
3. 添加 Analytics 范围
进入 OAuth 同意屏幕 > 数据访问(或范围),添加:
https://www.googleapis.com/auth/analytics.readonly
Google 将其列为敏感范围。如果您的应用是内部模式,则无需验证。
4. 启用 Analytics Data API
访问:https://console.cloud.google.com/apis/library/analyticsdata.googleapis.com
点击启用。
5. 创建 OAuth 2.0 凭据
进入 API 和服务 > 凭据 > 创建凭据 > OAuth 客户端 ID
保存客户端 ID 和客户端密钥。
6. 获取您的 GA4 媒体资源 ID
访问 https://analytics.google.com > 管理(齿轮图标)> 媒体资源设置。媒体资源 ID 是顶部的数字值。
7. 生成刷新令牌
在本地机器上运行以下命令(需要浏览器进行 Google 登录流程):
bash
pip install google-auth-oauthlib
bash
python3 -c from googleauthoauthlib.flow import InstalledAppFlow; flow = InstalledAppFlow.fromclientconfig({installed: {clientid: YOURCLIENTID, clientsecret: YOURCLIENTSECRET, authuri: https://accounts.google.com/o/oauth2/auth, tokenuri: https://oauth2.googleapis.com/token}}, scopes=[https://www.googleapis.com/auth/analytics.readonly]); creds = flow.runlocalserver(port=0); print(REFRESH TOKEN:, creds.refresh_token)
将 YOURCLIENTID 和 YOURCLIENTSECRET 替换为您的实际值。浏览器窗口将打开,供您使用 Google 账号登录。从输出中复制刷新令牌。
8. 设置环境变量
GA4PROPERTYID=123456789
GOOGLECLIENTID=您的客户端ID
GOOGLECLIENTSECRET=您的客户端密钥
GOOGLEREFRESHTOKEN=您的刷新令牌
故障排除
- - 403 HTML 错误页面:可能未将 analytics.readonly 范围添加到 OAuth 同意屏幕。请前往数据访问/范围添加该范围,然后重新生成刷新令牌。
- 403 JSON 错误调用者没有权限:您的 Google 账号无权访问该 GA4 媒体资源。请在 Google Analytics 中检查管理 > 媒体资源访问管理。
- 令牌刷新失败:您的刷新令牌可能已过期。请使用步骤 7 重新生成。
查询
按页面浏览量排名的热门页面
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics screenPageViews \
--dimension pagePath \
--limit 20
包含会话数和用户数的热门页面
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics screenPageViews,sessions,totalUsers \
--dimension pagePath \
--limit 20
流量来源
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics sessions \
--dimension sessionSource \
--limit 20
按来源和媒介划分的流量
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics sessions,totalUsers,conversions \
--dimensions sessionSource,sessionMedium \
--limit 20
落地页
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics sessions,bounceRate \
--dimension landingPage \
--limit 30
自定义日期范围
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics screenPageViews,sessions \
--dimension pagePath \
--start 2026-01-01 \
--end 2026-01-31 \
--limit 20
按路径前缀筛选
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics screenPageViews,sessions \
--dimension pagePath \
--filter pagePath=~/blog/ \
--limit 20
按广告系列划分的转化
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics conversions,sessions \
--dimensions sessionCampaignName,sessionSource \
--limit 20
设备细分
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics sessions,totalUsers \
--dimension deviceCategory \
--limit 10
国家/地区细分
bash
python3 /mnt/skills/user/google-analytics/scripts/ga4_query.py \
--metrics sessions,totalUsers \
--dimension country \
--limit 20
常用指标
screenPageViews(屏幕页面浏览量)、sessions(会话数)、totalUsers(总用户数)、newUsers(新用户数)、activeUsers(活跃用户数)、bounceRate(跳出率)、averageSessionDuration(平均会话时长)、conversions(转化数)、eventCount(事件计数)、engagementRate(互动率)、userEngagementDuration(用户互动时长)
常用维度
pagePath(页面路径)、pageTitle(页面标题)、landingPage(落地页)、sessionSource(会话来源)、sessionMedium(会话媒介)、sessionCampaignName(会话广告系列名称)、country(国家/地区)、city(城市)、deviceCategory(设备类别)、browser(浏览器)、date(日期)、week(周)、month(月)
输出
结果以格式化表格形式输出到标准输出。如果需要原始 JSON 格式,请通过管道传递给 | python3 -m json.tool。