返回文章列表
Hypereal AI Team
APITutorialVideo
YouTube Data API:开发者全指南 (2026)
如何以编程方式搜索、列出及管理 YouTube 内容
11 min read
100+ AI 模型,一个 API
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
YouTube Data API:开发者全指南 (2026)
YouTube Data API v3 允许你将 YouTube 功能集成到你的应用程序中。你可以通过编程方式搜索视频、获取频道信息、管理播放列表、读取评论等。
本指南涵盖了入门所需的一切:设置 API 访问、发起首次请求,以及通过实用的代码示例构建常见功能。
入门指南
步骤 1:创建 Google Cloud 项目
- 访问 console.cloud.google.com
- 创建一个新项目(或选择现有项目)
- 导航至 APIs & Services > Library
- 搜索 "YouTube Data API v3" 并启用它
步骤 2:创建 API 凭据
根据你的使用场景,有两种选择:
| 凭据类型 | 使用场景 | 访问权限 |
|---|---|---|
| API Key | 公开数据(搜索、视频详情) | 只读,无需用户授权 |
| OAuth 2.0 | 用户数据(播放列表、订阅、上传) | 需用户同意的读/写权限 |
获取 API Key:
- 前往 APIs & Services > Credentials
- 点击 Create Credentials > API Key
- (可选)限制该密钥仅用于 YouTube Data API
获取 OAuth 2.0:
- 前往 APIs & Services > Credentials
- 点击 Create Credentials > OAuth client ID
- 配置同意屏幕(consent screen)
- 选择应用程序类型(Web、Desktop 等)
- 记录你的 Client ID 和 Client Secret
步骤 3:安装客户端库
# Python
pip install google-api-python-client google-auth-oauthlib
# Node.js
npm install googleapis
# Go
go get google.golang.org/api/youtube/v3
API Key 身份验证(公开数据)
对于读取公开数据(如搜索视频或获取频道信息),使用 API key 就足够了:
Python
from googleapiclient.discovery import build
API_KEY = "YOUR_API_KEY"
youtube = build("youtube", "v3", developerKey=API_KEY)
JavaScript (Node.js)
import { google } from "googleapis";
const youtube = google.youtube({
version: "v3",
auth: "YOUR_API_KEY",
});
搜索视频
search.list 接口是最常用的端点。它支持按关键词、频道、位置等进行搜索。
基础搜索
def search_videos(query, max_results=10):
request = youtube.search().list(
part="snippet",
q=query,
type="video",
maxResults=max_results,
order="relevance"
)
response = request.execute()
videos = []
for item in response["items"]:
videos.append({
"title": item["snippet"]["title"],
"videoId": item["id"]["videoId"],
"channel": item["snippet"]["channelTitle"],
"published": item["snippet"]["publishedAt"],
"thumbnail": item["snippet"]["thumbnails"]["high"]["url"],
})
return videos
# 使用示例
results = search_videos("python tutorial 2026")
for video in results:
print(f"{video['title']} - https://youtube.com/watch?v={video['videoId']}")
JavaScript 版本
async function searchVideos(query, maxResults = 10) {
const response = await youtube.search.list({
part: "snippet",
q: query,
type: "video",
maxResults: maxResults,
order: "relevance",
});
return response.data.items.map((item) => ({
title: item.snippet.title,
videoId: item.id.videoId,
channel: item.snippet.channelTitle,
published: item.snippet.publishedAt,
thumbnail: item.snippet.thumbnails.high.url,
}));
}
const results = await searchVideos("javascript tutorial 2026");
搜索参数
| 参数 | 说明 | 示例 |
|---|---|---|
q |
搜索查询关键词 | "python machine learning" |
type |
资源类型 | "video", "channel", "playlist" |
order |
排序方式 | "relevance", "date", "viewCount", "rating" |
maxResults |
每页结果数 (1-50) | 25 |
publishedAfter |
按日期过滤 | "2026-01-01T00:00:00Z" |
channelId |
在特定频道内搜索 | "UCxxxxxxxx" |
videoDuration |
按时长过滤 | "short", "medium", "long" |
regionCode |
地区结果 | "US", "GB", "JP" |
relevanceLanguage |
语言倾向 | "en", "es" |
获取视频详情
videos.list 接口提供有关特定视频的详细信息:
def get_video_details(video_ids):
"""获取一个或多个视频的详细信息。"""
request = youtube.videos().list(
part="snippet,statistics,contentDetails",
id=",".join(video_ids)
)
response = request.execute()
videos = []
for item in response["items"]:
videos.append({
"title": item["snippet"]["title"],
"description": item["snippet"]["description"],
"channel": item["snippet"]["channelTitle"],
"published": item["snippet"]["publishedAt"],
"duration": item["contentDetails"]["duration"],
"views": int(item["statistics"].get("viewCount", 0)),
"likes": int(item["statistics"].get("likeCount", 0)),
"comments": int(item["statistics"].get("commentCount", 0)),
"tags": item["snippet"].get("tags", []),
})
return videos
# 使用示例
details = get_video_details(["dQw4w9WgXcQ"])
print(f"Views: {details[0]['views']:,}")
可用 Part
| Part | 包含的数据 | 配额成本 |
|---|---|---|
snippet |
标题、描述、缩略图、标签 | 2 |
statistics |
观看次数、点赞数、评论数 | 2 |
contentDetails |
时长、分辨率、字幕 | 2 |
status |
隐私状态、许可证、是否可嵌入 | 2 |
player |
嵌入 HTML 代码 | 0 |
topicDetails |
主题分类 | 2 |
获取频道信息
def get_channel_info(channel_id):
request = youtube.channels().list(
part="snippet,statistics,brandingSettings",
id=channel_id
)
response = request.execute()
if not response["items"]:
return None
channel = response["items"][0]
return {
"name": channel["snippet"]["title"],
"description": channel["snippet"]["description"],
"subscribers": int(channel["statistics"].get("subscriberCount", 0)),
"totalViews": int(channel["statistics"].get("viewCount", 0)),
"videoCount": int(channel["statistics"].get("videoCount", 0)),
"thumbnail": channel["snippet"]["thumbnails"]["high"]["url"],
"customUrl": channel["snippet"].get("customUrl", ""),
}
# 使用示例
channel = get_channel_info("UC_x5XG1OV2P6uZZ5FSM9Ttw") # Google Developers
print(f"{channel['name']}: {channel['subscribers']:,} subscribers")
操作播放列表
列出频道的播放列表
def get_channel_playlists(channel_id, max_results=25):
request = youtube.playlists().list(
part="snippet,contentDetails",
channelId=channel_id,
maxResults=max_results
)
response = request.execute()
return [{
"title": item["snippet"]["title"],
"playlistId": item["id"],
"videoCount": item["contentDetails"]["itemCount"],
"description": item["snippet"]["description"],
} for item in response["items"]]
获取播放列表中的视频
def get_playlist_videos(playlist_id):
videos = []
next_page_token = None
while True:
request = youtube.playlistItems().list(
part="snippet",
playlistId=playlist_id,
maxResults=50,
pageToken=next_page_token
)
response = request.execute()
for item in response["items"]:
videos.append({
"title": item["snippet"]["title"],
"videoId": item["snippet"]["resourceId"]["videoId"],
"position": item["snippet"]["position"],
})
next_page_token = response.get("nextPageToken")
if not next_page_token:
break
return videos
# 使用示例:获取播放列表中的所有视频
videos = get_playlist_videos("PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH")
print(f"Found {len(videos)} videos in playlist")
读取评论
def get_video_comments(video_id, max_results=20):
request = youtube.commentThreads().list(
part="snippet",
videoId=video_id,
maxResults=max_results,
order="relevance",
textFormat="plainText"
)
response = request.execute()
comments = []
for item in response["items"]:
comment = item["snippet"]["topLevelComment"]["snippet"]
comments.append({
"author": comment["authorDisplayName"],
"text": comment["textDisplay"],
"likes": comment["likeCount"],
"published": comment["publishedAt"],
})
return comments
# 使用示例
comments = get_video_comments("dQw4w9WgXcQ")
for c in comments[:5]:
print(f"{c['author']}: {c['text'][:100]}")
分页处理
YouTube API 响应是分页的。使用 nextPageToken 来获取后续页面:
def search_all_videos(query, max_total=100):
"""带自动分页的搜索。"""
all_results = []
next_page_token = None
while len(all_results) < max_total:
request = youtube.search().list(
part="snippet",
q=query,
type="video",
maxResults=min(50, max_total - len(all_results)),
pageToken=next_page_token
)
response = request.execute()
for item in response["items"]:
all_results.append({
"title": item["snippet"]["title"],
"videoId": item["id"]["videoId"],
})
next_page_token = response.get("nextPageToken")
if not next_page_token:
break
return all_results
配额管理
YouTube Data API 使用配额系统。你每天的基础配额为 10,000 个单位(免费层级)。
各操作的配额成本
| 操作 | 配额成本 |
|---|---|
search.list |
100 |
videos.list |
每个 part 计 1 消耗 |
channels.list |
每个 part 计 1 消耗 |
playlists.list |
每个 part 计 1 消耗 |
playlistItems.list |
每个 part 计 1 消耗 |
commentThreads.list |
1 |
videos.insert (上传) |
1,600 |
videos.update |
50 |
videos.delete |
50 |
配额优化技巧
- 尽量减少搜索调用 ——
search.list成本高达 100 单位。请缓存结果。 - 批量处理视频 ID ——
videos.list在一次请求中最多接受 50 个 ID。 - 只请求必要的 part —— 每一个
part都会增加成本。 - 使用
fields参数 —— 减少响应大小(虽然不减少配额,但能加快请求速度)。
# 高效:批量请求多个视频
request = youtube.videos().list(
part="statistics", # 只请求你需要的
id="id1,id2,id3,id4,id5", # 批量处理最多 50 个 ID
fields="items(id,statistics/viewCount)" # 仅返回需要的字段
)
申请更高配额
如果每天 10,000 单位不够用:
- 前往 Google Cloud Console > APIs & Services > YouTube Data API v3
- 点击 Quotas,然后点击 Request Quota Increase
- 填写表格解释你的使用场景
- Google 通常会在几个工作日内答复
错误处理
from googleapiclient.errors import HttpError
def safe_search(query):
try:
request = youtube.search().list(
part="snippet",
q=query,
type="video",
maxResults=10
)
return request.execute()
except HttpError as e:
status = e.resp.status
if status == 403:
error_reason = e.error_details[0]["reason"] if e.error_details else ""
if error_reason == "quotaExceeded":
print("Daily quota exceeded. Try again tomorrow.")
else:
print(f"Forbidden: {error_reason}")
elif status == 400:
print(f"Bad request: {e}")
elif status == 404:
print("Resource not found")
else:
print(f"HTTP {status}: {e}")
return None
常见使用场景
构建视频仪表板
def get_channel_dashboard(channel_id):
"""获取 YouTube 频道的完整仪表板数据。"""
# 获取频道信息
channel = get_channel_info(channel_id)
# 获取最新上传 (上传播放列表 ID = "UU" + channel_id[2:])
uploads_playlist_id = "UU" + channel_id[2:]
recent_videos = get_playlist_videos(uploads_playlist_id)[:10]
# 获取最新上传视频的详情
video_ids = [v["videoId"] for v in recent_videos]
video_details = get_video_details(video_ids)
return {
"channel": channel,
"recentVideos": video_details,
"totalViews": sum(v["views"] for v in video_details),
"avgViews": sum(v["views"] for v in video_details) // len(video_details),
}
追踪视频表现随时间的变化
import json
from datetime import datetime
def track_video_stats(video_id, output_file="stats.json"):
"""记录视频统计数据用于趋势分析。"""
details = get_video_details([video_id])[0]
entry = {
"timestamp": datetime.now().isoformat(),
"views": details["views"],
"likes": details["likes"],
"comments": details["comments"],
}
# 追加到 JSON 文件
try:
with open(output_file, "r") as f:
data = json.load(f)
except FileNotFoundError:
data = []
data.append(entry)
with open(output_file, "w") as f:
json.dump(data, f, indent=2)
print(f"Recorded: {entry['views']:,} views, {entry['likes']:,} likes")
速率限制与最佳实践
| 最佳实践 | 说明 |
|---|---|
| 缓存响应 | 将搜索结果存储在本地,避免重复调用 API |
| 使用 ETags | 在条件请求中包含 If-None-Match 请求头 |
| 批量请求 | 将多个视频 ID 合并到单个 videos.list 调用中 |
| 智慧分页 | 仅在需要时才抓取后续页面 |
| 监控配额使用 | 每天查看 Google Cloud Console 配额仪表板 |
| 使用 webhooks 监听变更 | 考虑使用 YouTube Push Notifications 获取实时更新 |
总结
YouTube Data API 功能强大且文档齐全,但配额管理至关重要。请通过缓存、批量处理和选择性 Part 请求来优化你的应用。
对于构建视频相关应用的开发者,YouTube Data API 与 AI 视频生成工具相得益彰。Hypereal AI 提供的 API 可生成 AI 视频、数字人头像和图像内容,你可以将这些内容上传到 YouTube,或在应用中与 YouTube 内容协同使用。
