通过托管 OAuth 代理访问 YouTube Data API v3,搜索与管理视频、播放列表、频道、订阅和评论。
设计与多媒体
YouTube Analytics
试用通过托管 OAuth 接入 YouTube Analytics 接口,查询频道报告并管理分析分组。
它能做什么
通过 YouTube Analytics 接口获取频道表现数据,涵盖观看次数、观看时长、订阅变化和收入等指标。所有请求统一走 Maton 网关(基础地址 https://api.maton.ai/youtube-analytics/),由 Maton 自动注入 OAuth 令牌并转发到 youtubeanalytics.googleapis.com。同时支持列出、创建、更新(仅标题)和删除分析分组,分组用于聚合视频、播放列表、频道或合作伙伴资产,单个分组最多 500 条。报告接口为只读,不会改动频道数据;所有针对分组及分组条目的写操作执行前都需要用户明确确认。
什么时候用它
- 按日或按月查询频道观看次数与观看时长
- 按国家、设备类型或操作系统拆分观看表现
- 创建视频或播放列表分组,统一分析高表现内容
- 梳理现有分析分组并移除其中的条目
技能文档
YouTube Analytics
Access the YouTube Analytics API with managed OAuth authentication. Retrieve channel performance reports (views, watch time, subscribers, revenue) and manage analytics groups for aggregating videos, playlists, or channels.
Quick Start
# Get channel views and watch time for the last 30 days
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/youtube-analytics/v2/reports?ids=channel==MINE&startDate=2025-04-01&endDate=2025-04-30&metrics=views,estimatedMinutesWatched,averageViewDuration')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Base URL
https://api.maton.ai/youtube-analytics/{native-api-path}
Maton proxies requests to youtubeanalytics.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 YouTube Analytics OAuth connections at https://api.maton.ai.
List Connections
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/connections?app=youtube-analytics&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
python <<'EOF'
import urllib.request, os, json
data = json.dumps({'app': 'youtube-analytics'}).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": "youtube-analytics",
"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 YouTube 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/youtube-analytics/v2/reports?ids=channel==MINE&startDate=2025-01-01&endDate=2025-01-31&metrics=views')
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
- Access is scoped to the YouTube channel(s) associated with the connected Google account.
- Reports are read-only and do not modify channel data.
- Group management operations (create, update, delete) require explicit user approval. Before executing any group or group item modification, confirm the target resource and intended effect with the user.
API Reference
Reports
Query Reports
GET /youtube-analytics/v2/reports?ids={channel_id}&startDate={start}&endDate={end}&metrics={metrics}
Required Parameters:
| Parameter | Type | Description |
|---|---|---|
ids | string | Channel identifier: channel==MINE or channel==CHANNEL_ID |
startDate | string | Start date in YYYY-MM-DD format |
endDate | string | End date in YYYY-MM-DD format |
metrics | string | Comma-separated metrics (e.g., views,likes,comments) |
Optional Parameters:
| Parameter | Type | Description |
|---|---|---|
dimensions | string | Comma-separated dimensions (e.g., day, month, country, video) |
filters | string | Filters in format dimension==value (e.g., country==US) |
sort | string | Sort field; prefix with - for descending (e.g., -views) |
maxResults | integer | Maximum rows to return |
startIndex | integer | 1-based pagination start index |
currency | string | ISO 4217 currency code for revenue metrics (default: USD) |
Example - Daily views for a month:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/youtube-analytics/v2/reports?ids=channel==MINE&startDate=2025-03-01&endDate=2025-03-31&metrics=views,estimatedMinutesWatched,averageViewDuration&dimensions=day&sort=-views&maxResults=10')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Example - Monthly summary:
python <<'EOF'
import urllib.request, os, json
req = urllib.request.Request('https://api.maton.ai/youtube-analytics/v2/reports?ids=channel==MINE&startDate=2024-01-01&endDate=2024-12-01&metrics=views,likes,shares,subscribersGained,subscribersLost&dimensions=month&sort=-views')
req.add_header('Authorization', f'Bearer {os.environ["MATON_API_KEY"]}')
print(json.dumps(json.load(urllib.request.urlopen(req)), indent=2))
EOF
Response:
{
"kind": "youtubeAnalytics#resultTable",
"columnHeaders": [
{
"name": "day",
"columnType": "DIMENSION",
"dataType": "STRING"
},
{
"name": "views",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"rows": [
["2025-03-12", 4],
["2025-03-15", 2]
]
}
Common Metrics:
views- Total video viewslikes- Total likesdislikes- Total dislikescomments- Total commentsshares- Total sharesestimatedMinutesWatched- Total watch time in minutesaverageViewDuration- Average view duration in secondssubscribersGained- New subscribers gainedsubscribersLost- Subscribers lostaverageViewPercentage- Average percentage of video watchedcardClickRate- Card click rate
Common Dimensions:
day- Daily aggregation (YYYY-MM-DD)month- Monthly aggregation (YYYY-MM); endDate must align to 1st of monthcountry- ISO 3166-1 alpha-2 country codevideo- Per-video breakdowndeviceType- Device type (DESKTOP, MOBILE, TABLET, TV, etc.)operatingSystem- OS (ANDROID, IOS, WINDOWS, etc.)liveOrOnDemand- LIVE or ON_DEMANDsubscribedStatus- SUBSCRIBED or UNSUBSCRIBED
Groups
List Groups
GET /youtube-analytics/v2/groups?mine=true
Or by specific IDs:
GET /youtube-analytics/v2/groups?id={group_id}
Parameters:
| Parameter | Type | Description |
|---|---|---|
mine | boolean | Set to true to retrieve all groups owned by authenticated user |
id | string | Comma-separated group IDs to retrieve |
pageToken | string | Token for paginating results |
Response:
{
"kind": "youtube#groupListResponse",
"items": [
{
"kind": "youtube#group",
"etag": "CQVfQEQY1xqZ2O8xKat5QfS2cik",
"id": "JiAz5ne9Wwk",
"snippet": {
"title": "My Video Group",
"publishedAt": "2026-05-04T22:02:12Z"
},
"contentDetails": {
"itemType": "youtube#video"
}
}
],
"nextPageToken": "..."
}
Create Group
POST /youtube-analytics/v2/groups
Content-Type: application/json
{
"snippet": {
"title": "My New Group"
},
"contentDetails": {
"itemType": "youtube#video"
}
}
Valid item types: youtube#video, youtube#playlist, youtube#channel, youtubePartner#asset
Example:
python <<'EOF'
import urllib.request, os, json
data = json.dumps({
"snippet": {"title": "Top Performers"},
"contentDetails": {"itemType": "youtube#video"}
}).encode()
req = urllib.request.Request('https://api.maton.ai/youtube-analytics/v2/groups', 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
Update Group
PUT /youtube-analytics/v2/groups
Content-Type: application/json
{
"id": "{group_id}",
"snippet": {
"title": "Updated Title"
},
"contentDetails": {
"itemType": "youtube#video"
}
}
Only the group title can be updated.
Delete Group
DELETE /youtube-analytics/v2/groups?id={group_id}
Group Items
List Group Items
GET /youtube-analytics/v2/groupItems?groupId={group_id}
Response:
{
"kind": "youtube#groupItemListResponse",
"etag": "...",
"items": [
{
"kind": "youtube#groupItem",
"etag": "...",
"groupId": "JiAz5ne9Wwk",
"resource": {
"kind": "youtube#video",
"id": "VIDEO_ID"
}
}
]
}
Add Item to Group
POST /youtube-analytics/v2/groupItems
Content-Type: application/json
{
"groupId": "{group_id}",
"resource": {
"kind": "youtube#video",
"id": "{video_id}"
}
}
Returns 201 on success, 204 if item already exists in group. Maximum 500 items per group.
Remove Item from Group
DELETE /youtube-analytics/v2/groupItems?id={group_item_id}
Pagination
Reports
Use startIndex and maxResults for paginating report results:
GET /youtube-analytics/v2/reports?ids=channel==MINE&startDate=2025-01-01&endDate=2025-03-31&metrics=views&dimensions=day&maxResults=30&startIndex=1
startIndex is 1-based. Increment by maxResults for subsequent pages.
Groups
Use token-based pagination:
GET /youtube-analytics/v2/groups?mine=true&pageToken={nextPageToken}
Response includes nextPageToken when more results exist.
Code Examples
JavaScript
const response = await fetch(
'https://api.maton.ai/youtube-analytics/v2/reports?ids=channel==MINE&startDate=2025-01-01&endDate=2025-01-31&metrics=views,likes,comments&dimensions=day&sort=-views',
{
headers: {
'Authorization': `Bearer ${process.env.MATON_API_KEY}`
}
}
);
const data = await response.json();
console.log(data.rows);
Python
import os
import requests
response = requests.get(
'https://api.maton.ai/youtube-analytics/v2/reports',
headers={'Authorization': f'Bearer {os.environ["MATON_API_KEY"]}'},
params={
'ids': 'channel==MINE',
'startDate': '2025-01-01',
'endDate': '2025-01-31',
'metrics': 'views,likes,comments',
'dimensions': 'day',
'sort': '-views'
}
)
data = response.json()
for row in data.get('rows', []):
print(row)
Notes
- Dates must be in
YYYY-MM-DDformat - When using
monthdimension,endDatemust align to the 1st of a month (e.g.,2024-12-01not2024-12-31) ids=channel==MINEuses the authenticated user's channel; usechannel==CHANNEL_IDfor a specific channel- Groups can contain a maximum of 500 items, all of the same resource type
- Only the group title can be updated via
groups.update; usegroupItemsmethods to manage membership - Adding items to a group requires the items to be owned by the authenticated channel
- IMPORTANT: When using curl commands, use
curl -gwhen URLs contain brackets 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
Error Handling
| Status | Meaning |
|---|---|
| 400 | Bad request (invalid date range, misaligned month dimension, missing required params) |
| 401 | Invalid or missing Maton API key |
| 403 | Forbidden (insufficient permissions or trying to add items not owned by channel) |
| 429 | Rate limited |
| 4xx/5xx | Passthrough error from YouTube Analytics API |
Troubleshooting: API Key Issues
- 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
youtube-analytics. For example:
- Correct:
https://api.maton.ai/youtube-analytics/v2/reports?... - Incorrect:
https://api.maton.ai/v2/reports?...
Resources
常见问题
- 这个技能会修改 YouTube 频道数据吗?
- 不会。报告接口为只读,不会改动频道数据。只有分组与分组条目的管理接口(创建、更新、删除)会产生写操作,且执行前都需要用户明确确认。
- 支持哪些指标和维度?
- 常用指标包括 views、likes、dislikes、comments、shares、estimatedMinutesWatched、averageViewDuration、subscribersGained、subscribersLost、averageViewPercentage、cardClickRate 等。常用维度包括 day、month、country、video、deviceType、operatingSystem、liveOrOnDemand、subscribedStatus。收入类指标可通过 currency 参数指定 ISO 4217 货币代码,默认 USD。
- 身份验证是如何处理的?
- 由 Maton 负责托管 OAuth。调用时在 Authorization 头里传入 Maton API Key(取自 $MATON_API_KEY),Maton 会注入 YouTube OAuth 令牌并把请求转发到 youtubeanalytics.googleapis.com。如果绑定了多个 YouTube Analytics 连接,需通过 Maton-Connection 头指定要使用的连接。
相关技能
通过托管 OAuth 调度 YouTube Reporting 批量任务,下载频道与播放列表的每日 CSV 报告。
通过托管 OAuth 连接访问 Google Analytics,运行报表并管理分析资源配置。
通过托管 OAuth,使用 GAQL 查询 Google Ads 广告系列、关键词和效果数据。
通过托管 OAuth 代理接入 Google Search Console,查询搜索分析数据、管理 sitemap 并查看站点表现。
通过 OAuth 托管的 API 创建与管理 Google Apps Script 项目、部署、版本及远程脚本执行。