通过托管 OAuth,使用 GAQL 查询 Google Ads 广告系列、关键词和效果数据。
文档
google-analytics
试用通过托管 OAuth 连接访问 Google Analytics,运行报表并管理分析资源配置。
它能做什么
通过托管 OAuth 代理接入 Google Analytics 官方的 Admin API 与 Data API。Data API 仅支持读取,可按维度运行会话、用户、页面浏览、转化等指标的报表。Admin API 具备写权限,可管理账号、属性、数据流、自定义维度和转化事件;任何 POST、PATCH、DELETE 在执行前都必须先向用户明确展示目标资源并取得确认。认证使用 Bearer Token (MATON_API_KEY) 调用 api.maton.ai,Admin 与 Data 使用各自独立的 OAuth 连接。
什么时候用它
- 按维度拉取活跃用户、会话、转化等指标报表
- 通过 Admin API 列出账号、属性和数据流
- 经用户确认后创建或更新自定义维度和转化事件
- 运行批量报表与实时报表
技能文档
Google Analytics
Access Google Analytics with managed OAuth authentication. This skill covers both the Admin API (manage accounts, properties, data streams) and the Data API (run reports on metrics).
Quick Start
# List account summaries (Admin API)
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/google-analytics-admin/v1beta/accountSummaries')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
# Run a report (Data API)
python <<'EOF'
import urllib.request, os, json
data = json.dumps({'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], 'dimensions': [{'name': 'city'}], 'metrics': [{'name': 'activeUsers'}]}).encode()
req = urllib.request.Request('https://api.maton.ai/google-analytics-data/v1beta/properties/{propertyId}:runReport', data=data, method='POST')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Content-Type', 'application/json')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Base URLs
Data API (read-only — run reports):
https://api.maton.ai/google-analytics-data/{native-api-path}
Admin API (write-capable — manage accounts, properties, data streams):
https://api.maton.ai/google-analytics-admin/{native-api-path}
Prefer the Data API for reporting tasks. Use the Admin API only when the user explicitly needs to create, update, or delete analytics configuration. Admin API mutations are high-impact — changes to properties and data streams affect analytics data collection.
Maton proxies requests to analyticsadmin.googleapis.com and analyticsdata.googleapis.com and automatically injects your OAuth token.
Authentication
All requests require the Maton API key in the Authorization header:
Authorization: Bearer $MATON_API_KEY
Environment Variable: Set your API key as MATON_API_KEY:
export MATON_API_KEY="YOUR_API_KEY"
Getting Your API Key
- Sign in or create an account at maton.ai
- Go to maton.ai/settings
- Copy your API key
Connection Management
Manage your Google OAuth connections at https://api.maton.ai.
Important: The Admin API and Data API use separate connections:
google-analytics-admin- Required for Admin API endpoints (manage accounts, properties, data streams)google-analytics-data- Required for Data API endpoints (run reports)
Create the connection(s) you need based on which API you want to use.
List Connections
# List Admin API connections
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections?app=google-analytics-admin&status=ACTIVE')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
# List Data API connections
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections?app=google-analytics-data&status=ACTIVE')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Create Connection
# Create Admin API connection (for managing accounts, properties, data streams)
python <<'EOF'
import urllib.request, os, json
data = json.dumps({'app': 'google-analytics-admin'}).encode()
req = urllib.request.Request('https://api.maton.ai/connections', data=data, method='POST')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Content-Type', 'application/json')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
# Create Data API connection (for running reports)
python <<'EOF'
import urllib.request, os, json
data = json.dumps({'app': 'google-analytics-data'}).encode()
req = urllib.request.Request('https://api.maton.ai/connections', data=data, method='POST')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Content-Type', 'application/json')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Get Connection
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections/{connection_id}')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Response:
{
"connection": {
"connection_id": "{connection_id}",
"status": "ACTIVE",
"creation_time": "2025-12-08T07:20:53.488460Z",
"last_updated_time": "2026-01-31T20:03:32.593153Z",
"url": "https://connect.maton.ai/?session_token=...",
"app": "google-analytics-admin",
"metadata": {}
}
}
Open the returned url in a browser to complete OAuth authorization.
Delete Connection
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections/{connection_id}', method='DELETE')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Specifying Connection
If you have multiple Google Analytics connections, specify which one to use with the Maton-Connection header:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/google-analytics-admin/v1beta/accountSummaries')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
req.add_header('Maton-Connection', '{connection_id}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
If you have multiple connections, always include this header to ensure requests go to the intended account.
Security & Permissions
- Prefer the Data API connection for reporting tasks. The Data API is read-only and cannot modify analytics configuration. Only create an Admin API connection when the user explicitly needs administrative changes.
- Access is scoped to properties, data streams, reports, and analytics data within the connected Google Analytics account. Revoke unused connections promptly — especially Admin API connections when administrative work is complete.
- Default to read-only operations. Always start by listing or retrieving resources to confirm account, property, and data stream identifiers before proposing any changes.
- All Admin API write operations require explicit user approval with specific identifiers. Before executing any POST, PATCH, or DELETE call:
- Retrieve and display the target resource (property name/ID, data stream name, account) so the user can verify.
- Clearly describe the intended effect (e.g., "This will delete data stream 'Web - example.com' (ID: 123456) from property 'My Site' — this will stop data collection").
- Wait for explicit user confirmation before proceeding.
- Admin API changes are high-impact and may be irreversible. Deleting properties or data streams stops data collection permanently. Modifying property settings can affect reporting accuracy. These actions must include a summary of consequences and require confirmation.
Admin API Reference
Accounts
GET /google-analytics-admin/v1beta/accounts
GET /google-analytics-admin/v1beta/accounts/{accountId}
GET /google-analytics-admin/v1beta/accountSummaries
Properties
GET /google-analytics-admin/v1beta/properties?filter=parent:accounts/{accountId}
GET /google-analytics-admin/v1beta/properties/{propertyId}
Create Property
POST /google-analytics-admin/v1beta/properties
Content-Type: application/json
{
"parent": "accounts/{accountId}",
"displayName": "My New Property",
"timeZone": "America/Los_Angeles",
"currencyCode": "USD"
}
Data Streams
GET /google-analytics-admin/v1beta/properties/{propertyId}/dataStreams
Create Web Data Stream
POST /google-analytics-admin/v1beta/properties/{propertyId}/dataStreams
Content-Type: application/json
{
"type": "WEB_DATA_STREAM",
"displayName": "My Website",
"webStreamData": {"defaultUri": "https://example.com"}
}
Custom Dimensions
GET /google-analytics-admin/v1beta/properties/{propertyId}/customDimensions
Create Custom Dimension
POST /google-analytics-admin/v1beta/properties/{propertyId}/customDimensions
Content-Type: application/json
{
"parameterName": "user_type",
"displayName": "User Type",
"scope": "USER"
}
Conversion Events
GET /google-analytics-admin/v1beta/properties/{propertyId}/conversionEvents
POST /google-analytics-admin/v1beta/properties/{propertyId}/conversionEvents
Data API Reference
Run Report
POST /google-analytics-data/v1beta/properties/{propertyId}:runReport
Content-Type: application/json
{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "city"}],
"metrics": [{"name": "activeUsers"}]
}
Run Realtime Report
POST /google-analytics-data/v1beta/properties/{propertyId}:runRealtimeReport
Content-Type: application/json
{
"dimensions": [{"name": "country"}],
"metrics": [{"name": "activeUsers"}]
}
Batch Run Reports
POST /google-analytics-data/v1beta/properties/{propertyId}:batchRunReports
Content-Type: application/json
{
"requests": [
{
"dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
"dimensions": [{"name": "country"}],
"metrics": [{"name": "sessions"}]
}
]
}
Get Metadata
GET /google-analytics-data/v1beta/properties/{propertyId}/metadata
Common Report Examples
Page Views by Page
{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "pagePath"}],
"metrics": [{"name": "screenPageViews"}],
"orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}],
"limit": 10
}
Users by Country
{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "country"}],
"metrics": [{"name": "activeUsers"}, {"name": "sessions"}]
}
Traffic Sources
{
"dateRanges": [{"startDate": "30daysAgo", "endDate": "today"}],
"dimensions": [{"name": "sessionSource"}, {"name": "sessionMedium"}],
"metrics": [{"name": "sessions"}, {"name": "conversions"}]
}
Common Dimensions
date,country,city,deviceCategorypagePath,pageTitle,landingPagesessionSource,sessionMedium,sessionCampaignName
Common Metrics
activeUsers,newUsers,sessionsscreenPageViews,bounceRate,averageSessionDurationconversions,eventCount
Date Formats
- Relative:
today,yesterday,7daysAgo,30daysAgo - Absolute:
2026-01-01
Code Examples
JavaScript
// List account summaries (Admin API)
const accounts = await fetch(
'https://api.maton.ai/google-analytics-admin/v1beta/accountSummaries',
{
headers: {
'Authorization': `Bearer ${process.env.MATON_API_KEY}`
}
}
);
// Run a report (Data API)
const report = await fetch(
'https://api.maton.ai/google-analytics-data/v1beta/properties/123456:runReport',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.MATON_API_KEY}`
},
body: JSON.stringify({
dateRanges: [{ startDate: '30daysAgo', endDate: 'today' }],
dimensions: [{ name: 'country' }],
metrics: [{ name: 'activeUsers' }]
})
}
);
Python
import os
import requests
# List account summaries (Admin API)
accounts = requests.get(
'https://api.maton.ai/google-analytics-admin/v1beta/accountSummaries',
headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'}
)
# Run a report (Data API)
report = requests.post(
'https://api.maton.ai/google-analytics-data/v1beta/properties/123456:runReport',
headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'},
json={
'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
'dimensions': [{'name': 'country'}],
'metrics': [{'name': 'activeUsers'}]
}
)
Notes
- GA4 properties only (Universal Analytics not supported)
- Property IDs are numeric (e.g.,
properties/521310447) - Use
accountSummariesto quickly list all accessible properties - Use
updateMaskfor PATCH requests in Admin API - Use metadata endpoint to discover available dimensions/metrics
- IMPORTANT: When using curl commands, use
curl -gwhen URLs contain brackets (fields[],sort[],records[]) to disable glob parsing - IMPORTANT: When piping curl output to
jqor other commands, environment variables like$MATON_API_KEYmay not expand correctly in some shell environments. You may get "Invalid API key" errors when piping.
Error Handling
| Status | Meaning |
|---|---|
| 400 | Missing Google Analytics connection |
| 401 | Invalid or missing Maton API key |
| 429 | Rate limited (10 req/sec per account) |
| 4xx/5xx | Passthrough error from Google Analytics API |
Troubleshooting: Invalid API Key
When you receive a "Invalid API key" error, ALWAYS follow these steps before concluding there is an issue:
- Check that the
MATON_API_KEYenvironment variable is set:
echo $MATON_API_KEY
- Verify the API key is valid by listing connections:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Troubleshooting: Invalid App Name
- Ensure your URL path starts with the correct app name:
- For Admin API: use
google-analytics-admin - For Data API: use
google-analytics-data
- For Admin API: use
Examples:
- Correct:
https://api.maton.ai/google-analytics-admin/v1beta/accountSummaries - Correct:
https://api.maton.ai/google-analytics-data/v1beta/properties/123456:runReport - Incorrect:
https://api.maton.ai/analytics/v1beta/accountSummaries
Resources
常见问题
- 报表类需求应该用哪个 API?
- 用 Data API。它只读,支持针对指定属性运行 runReport、runRealtimeReport、batchRunReports 以及元数据查询。
- Admin API 会改动我的分析配置吗?
- 会。它可以创建、更新或删除账号、属性、数据流、自定义维度和转化事件。删除属性或数据流不可逆,会立即停止数据采集,因此所有写入操作都必须先向用户展示目标资源并取得明确确认后才能执行。
相关技能
通过托管 OAuth 接入 GTM v2 API,对账户、容器、版本、代码、触发器和变量进行读写操作。
通过托管 OAuth 接入 YouTube Analytics 接口,查询频道报告并管理分析分组。
通过托管 OAuth 代理接入 Google Search Console,查询搜索分析数据、管理 sitemap 并查看站点表现。
通过托管 OAuth 连接,读写 Google Merchant Center 的商品、库存、促销与账户数据。
通过托管 OAuth 接入 Google Workspace Admin SDK,读取并管理用户、群组、组织单元、角色和域名,所有写操作必须经用户确认。