调用Youtube API v3指定子part参数报错(Python)
问题分析与解决方案
错误原因
Youtube Data API v3的part参数仅支持顶级资源片段名称,不能使用点语法指定嵌套的子字段。你设置的contentDetails.relatedPlaylists.uploads不是合法的part值,API无法识别,因此抛出未知part错误。
正确的做法是:先请求顶级的contentDetails片段,再从返回的响应数据中提取relatedPlaylists.uploads字段的值。
修正后的代码
import os import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube.readonly"] def main(): # 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_FILE.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) # 修正part参数为顶级片段contentDetails request = youtube.channels().list( part="contentDetails", id="UCtcUKdcAXfVCo5YlgBMkfjA" ) response = request.execute() # 从响应中提取上传列表ID if response.get('items'): uploads_playlist_id = response['items'][0]['contentDetails']['relatedPlaylists']['uploads'] print(f"上传列表ID: {uploads_playlist_id}") else: print("未找到对应频道数据") if __name__ == "__main__": main()
补充说明
- 所有Youtube API的
list接口,part参数都只能指定顶级资源片段(比如channels接口的合法part值包括snippet, contentDetails, statistics等)。 - 提取子字段时,建议加入空值判断(比如检查items是否存在),避免因API返回结构变化或频道不存在导致的KeyError。
内容的提问来源于stack exchange,提问作者orochi720x
相关产品推荐
相关产品推荐

