使用Youtube Data API v3添加视频到播放列表遇403错误,是否为Scope问题?
问题描述
我有一个视频列表,希望借助Youtube Data API v3将这些视频添加到播放列表中。已在代码及开发者控制台中完成OAuth配置,代码如下:
# Sample Python code for youtube.channels.list # See instructions for running these code samples locally: # https://developers.google.com/explorer-help/code-samples#python import os import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube"] # Disable OAuthlib's HTTPS verification when running locally. # *DO NOT* leave this option enabled in production. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" client_secrets_file = "client_secret_xxx.apps.googleusercontent.com.json" # Get credentials and create an API client flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console() youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials)
随后使用以下函数将视频添加到播放列表:
def add_video_to_playlist(youtube,videoID,playlistID): add_video_request=youtube.playlistItems().insert( part="snippet", body={ 'snippet': { 'playlistId': playlistID, 'resourceId': { 'kind': 'youtube#video', 'videoId': videoID } #'position': 0 } } ).execute()
开发者账户已设置对应Scope,但收到如下错误信息:
HttpError: <HttpError 403 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "Forbidden". Details: "[{'message': 'Forbidden', 'domain': 'youtube.playlistItem', 'reason': 'playlistItemsNotAccessible'}]">
请问哪里操作出错了?
排查方向及解决办法
这个playlistItemsNotAccessible错误大概率是以下几种情况导致的,逐一检查:
播放列表权限不匹配
你要操作的播放列表必须是当前OAuth授权账号创建的,或者该账号拥有这个播放列表的编辑权限。如果播放列表是其他账号的私有列表,你没有权限修改,就会触发这个错误。确认playlistID对应的播放列表归属正确,且你能在网页端手动编辑该列表。授权凭据未更新
虽然你在控制台设置了正确的Scope,但如果本地缓存了旧的授权凭据,实际请求可能用的是旧权限。找到本地凭据缓存目录(一般在~/.credentials/路径下),删除相关文件后重新运行代码,完成授权流程。目标资源状态异常
检查videoID对应的视频是否存在、是否为私密/受限视频;同时确认playlistID对应的播放列表没有被删除、没有设置为完全不可编辑。可以先手动在Youtube网页端尝试添加该视频到目标播放列表,验证资源本身是否正常。API参数拼写错误
核对playlistId和videoId的拼写是否完全正确,有没有多字符、少字符或者大小写错误。另外可以尝试取消注释position参数(比如设为0),看看是否能解决问题。
内容的提问来源于stack exchange,提问作者dlenker
相关产品推荐
相关产品推荐

