【发布时间】:2020-06-30 17:20:23
【问题描述】:
我正在尝试通过 Python 3.6 列出我的 YouTube 频道,给定(这很重要)一个现有的访问令牌和一些有效的 API 密钥。它适用于 curl 并返回有效的 JSON 响应:
curl 'https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true&key=API_KEY' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer ACCESS_TOKEN'
回复:
{
"kind": "youtube#channelListResponse",
"etag": "\"xxxxxxxxx\"",
"pageInfo": {...},
"items": [...]
}
如果我删除 Authorization 标头,我会收到预期的错误:
{
"error": {
"errors": [
{
"domain": "youtube.parameter",
"reason": "authorizationRequired",
"message": "The request uses the <code>mine</code> parameter but is not properly authorized.",
"locationType": "parameter",
"location": "mine"
}
],
"code": 401,
"message": "The request uses the <code>mine</code> parameter but is not properly authorized."
}
}
现在,我尝试对 Google Python 库做同样的事情(因为我需要它来进行更复杂的操作和代码控制),但它不起作用。我收到与未传递任何访问令牌相同的错误。任何想法我做错了什么?这是我的 Python 代码(请注意,访问令牌已提供给代码,我必须按原样使用它):
import argparse
import google.oauth2.credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def get_authenticated_service(options):
creds = google.oauth2.credentials.Credentials(options.access_token)
return build('youtube', 'v3', credentials=creds, developerKey=options.api_key)
def list_channels(youtube, options):
request = youtube.channels().list(part="snippet", mine=True)
response = request.execute()
print(response)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--api_key', required=True)
parser.add_argument('--access_token', required=True)
args = parser.parse_args()
youtube = get_authenticated_service(args)
try:
list_channels(youtube, args)
except HttpError as e:
print('An HTTP error {0} occurred:\n{1}'.format(e.resp.status, e.content))
我是这样运行的:
python3 test.py --api_key MY_API_KEY --access_token MY_ACCESS_TOKEN
【问题讨论】:
-
我认为您的脚本有效。那么比如
return build('youtube', 'v3', credentials=creds, developerKey=options.api_key)修改为return build('youtube', 'v3', credentials=creds),你会得到什么结果? -
很有趣,它不需要 api 密钥,但谷歌的原始 curl 示例(“列出我的频道”教程)指出 API_KEY 是必需的。我还手动测试了 CURL,实际上它也可以在没有 api 密钥的情况下工作。谢谢
-
感谢您的回复。我很高兴你的问题得到了解决。根据您的问题,我认为这可能对遇到相同问题的其他用户有用。因此,我将其发布为答案。你能确认一下吗?
标签: python-3.x youtube-data-api google-oauth