首页 > 解决方案 > 向 YouTube v3 Data API 发出请求时,我在哪里添加我的授权令牌?

问题描述

我目前正在使用 Python Requests 模块将视频添加到我创建的播放列表中。在 docs 上playlistItems.insert,它说需要对三个可能的范围之一进行授权。我在项目的凭据面板中创建了 OAUTH2.0 凭据令牌并正确设置了范围。目前我正在尝试按如下方式传递凭证:

payload = {
    'access_token': [My Client ID],
    'part': 'snippet'}
new_vid = requests.post(f'{base_url}playlistItems', params=payload)

执行代码时,我收到以下错误消息:

"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."

我是在正确的地方传递授权令牌,还是应该在POST请求中的其他地方传递它?

标签: pythonpython-requestsyoutube-apiyoutube-data-api

解决方案


您可以将授权令牌作为标头参数传递。检查以下示例:

import requests

headers = {
    'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
}

params = (
    ('key', '[YOUR_API_KEY]'),
    ('part','snippet')
)

response = requests.post('https://youtube.googleapis.com/youtube/v3/playlistItems', headers=headers, params=params)

推荐阅读