使用Google Auth Python库调用YouTube API获取订阅列表遇401认证错误
解决YouTube Data API订阅接口401无效凭证问题
问题根源
服务账户无法直接访问个人YouTube的订阅数据——订阅属于用户私有数据,服务账户没有关联你的个人YouTube账号权限,必须使用针对个人用户的OAuth2授权码流程,而非服务账户密钥认证。
步骤1:创建OAuth2客户端ID(替代服务账户)
- 登录Google Cloud控制台,进入你的项目,打开「API和服务」→「凭据」
- 点击「创建凭据」→「OAuth客户端ID」
- 应用类型选择「桌面应用」,填写名称后创建,下载生成的JSON文件(命名为
client_secret.json)
步骤2:正确的Python代码实现
使用google-auth-oauthlib和google-api-python-client库,实现带本地授权缓存的流程:
from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from google.auth.transport.requests import Request import os import pickle # 仅申请读取订阅的权限,遵循最小权限原则 SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'] def get_youtube_service(): creds = None # 读取本地缓存的授权凭证 if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # 刷新或重新获取凭证 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( 'client_secret.json', SCOPES) creds = flow.run_local_server(port=0) # 保存凭证到本地,避免重复授权 with open('token.pickle', 'wb') as token: pickle.dump(creds, token) return build('youtube', 'v3', credentials=creds) def list_subscriptions(service): # 调用订阅列表接口,获取当前授权用户的订阅 request = service.subscriptions().list( part='snippet', mine=True, maxResults=50 ) response = request.execute() # 打印订阅信息 for item in response['items']: print(f"订阅频道:{item['snippet']['title']}") print(f"频道ID:{item['snippet']['resourceId']['channelId']}\n") if __name__ == '__main__': service = get_youtube_service() list_subscriptions(service)
关键注意事项
- 不要使用服务账户密钥文件,必须用OAuth2客户端ID生成的
client_secret.json - 首次运行会自动弹出浏览器,要求你登录个人YouTube账号并授权应用访问订阅数据
- 授权成功后会生成
token.pickle,后续运行将自动复用该凭证,无需重复登录 - 确保你的Google Cloud项目已启用YouTube Data API v3(在API库中搜索启用)
内容的提问来源于stack exchange,提问作者misteralexander
相关产品推荐
相关产品推荐

