调用YouTube API时遭遇HttpError 403请求被拦截问题求助
YouTube API 调用返回HttpError 403 问题排查
我已将API令牌嵌入到YouTube API调用函数中,但仍收到HttpError 403响应。该函数直接复制自Google GitHub仓库中的search.py文件。
DEVELOPER_KEY = 'my_token_here' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' def youtube_search(): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. search_response = youtube.search().list( #q=options.q, part='id,snippet', #maxResults=options.max_results ).execute() videos = [] channels = [] playlists = [] # Add each result to the appropriate list, and then display the lists of # matching videos, channels, and playlists. for search_result in search_response.get('items', []): if search_result['id']['kind'] == 'youtube#video': videos.append('%s (%s)' % (search_result['snippet']['title'], search_result['id']['videoId'])) elif search_result['id']['kind'] == 'youtube#channel': channels.append('%s (%s)' % (search_result['snippet']['title'], search_result['id']['channelId'])) elif search_result['id']['kind'] == 'youtube#playlist': playlists.append('%s (%s)' % (search_result['snippet']['title'], search_result['id']['playlistId'])) print('Videos:\n', '\n'.join(videos), '\n') print('Channels:\n', '\n'.join(channels), '\n') print('Playlists:\n', '\n'.join(playlists), '\n')
调用youtube_search函数时,出现如下错误:
<HttpError 403 when requesting https://youtube.googleapis.com/youtube/v3/search?part=id%2Csnippet&key='my_token'=json returned "Requests to this API youtube method youtube.api.v3.V3DataSearchService.List are blocked.". Details: "[{'message': 'Requests to this API youtube method youtube.api.v3.V3DataSearchService.List are blocked.', 'domain': 'global', 'reason': 'forbidden'}]">
排查解决思路
- 确认API服务已启用:登录Google Cloud控制台,检查YouTube Data API v3是否处于启用状态。未启用服务是触发403的常见原因。
- 验证API密钥限制规则:查看密钥的IP/HTTP referrer限制设置,确保当前运行代码的环境符合限制规则。本地测试可暂时关闭限制来验证问题。
- 检查API配额是否耗尽:YouTube Data API有每日调用配额,search.list接口的配额消耗较高。去控制台配额页面确认是否已用完当日额度。
- 核对请求参数:尝试取消
q和maxResults的注释,填入合法参数(比如q="python"、maxResults=5)后重新测试,排除参数缺失导致的权限问题。 - 确认密钥正确性:再次检查
DEVELOPER_KEY中的令牌是否与控制台生成的完全一致,避免引号、空格等输入错误。
内容的提问来源于stack exchange,提问作者Bryson Crimmins
相关产品推荐
相关产品推荐

