如何获取权限通过YouTube Data API查询YouTube频道订阅列表?
解决YouTube Data API获取订阅列表的权限问题
先明确你要获取的订阅类型
首先得区分两种订阅列表的权限要求,这是解决问题的核心:
- 公开订阅列表:目标频道对外展示的已订阅内容,所有人可查看,只需用
API_KEY即可调用 - 私有订阅列表:特定用户的个人订阅数据(比如你自己的),必须通过OAuth 2.0授权才能访问
情况1:获取公开订阅列表的修复步骤
如果是拿别人频道公开的订阅列表,按以下步骤排查:
启用YouTube Data API v3
登录Google Cloud控制台,找到你的项目,搜索并启用"YouTube Data API v3"——没启用服务的话,直接会返回权限错误。检查API_KEY配置
- 确保API_KEY没有设置IP/HTTP referrer限制(本地测试别加这些,容易被拦截)
- 确认API_KEY绑定的项目已经启用了YouTube Data API
正确调用接口
必须用subscriptions.list接口,参数不能少:part=snippet,contentDetails(必填项)channelId:目标频道的ID(要获取哪个频道的订阅,就填这个)key:你的API_KEY
示例Python代码:
import googleapiclient.discovery def fetch_public_subs(api_key, target_channel_id): youtube = googleapiclient.discovery.build( "youtube", "v3", developerKey=api_key ) req = youtube.subscriptions().list( part="snippet,contentDetails", channelId=target_channel_id, maxResults=50 ) res = req.execute() for sub in res["items"]: print(f"订阅频道:{sub['snippet']['title']}") # 替换成你的API_KEY和目标频道ID fetch_public_subs("你的API_KEY", "目标频道ID")注意:如果目标频道设置了订阅列表不公开,那就算用API_KEY也拿不到,这是频道所有者的隐私设置,没法绕过。
情况2:获取私有订阅列表的修复步骤
如果要获取用户个人的私有订阅(比如你自己的),必须走OAuth授权:
- 创建OAuth客户端ID
到Google Cloud控制台的「API和服务」→「凭据」页面,创建「OAuth客户端ID」,应用类型选「桌面应用」(适合本地Python脚本),下载生成的credentials.json放到项目目录。 - 实现OAuth授权流程
用官方的google-auth和google-api-python-client库,示例代码:
运行后会弹出浏览器让你登录Google账号授权,授权后生成import os from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials # 只读订阅的权限范围,足够需求 SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"] def fetch_private_subs(): creds = None # 加载已保存的凭据(如果有) if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # 无有效凭据则触发授权流程 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", SCOPES ) creds = flow.run_local_server(port=0) # 保存凭据,下次不用重复授权 with open("token.json", "w") as f: f.write(creds.to_json()) youtube = build("youtube", "v3", credentials=creds) req = youtube.subscriptions().list( part="snippet,contentDetails", mine=True, # mine=True表示获取当前授权用户的订阅 maxResults=50 ) res = req.execute() for sub in res["items"]: print(f"订阅频道:{sub['snippet']['title']}") fetch_private_subs()token.json,后续运行直接用这个文件即可。
常见权限错误排查
- 403 Forbidden:
- 检查API_KEY是否绑定了已启用的YouTube Data API
- 查看Google Cloud控制台的API配额,免费配额是每天10000单位,
subscriptions.list每次调用耗1单位,配额用完也会返回403 - 如果是OAuth授权,确认权限范围是否正确,是否完成授权流程
- 404 Not Found:
- 检查
channelId是否正确,目标频道是否存在 - 用
mine=True时,确认授权的用户确实有订阅内容
- 检查
内容的提问来源于stack exchange,提问作者Freek Cool
相关产品推荐
相关产品推荐

