我试图通过Python3.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": [...]
}如果删除授权头,则会得到预期的错误:
{
"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代码(请注意,访问令牌给了代码,我必须按原样使用它):
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发布于 2020-03-20 09:13:50
我觉得你的剧本很管用。实际上,在我的环境中,我可以确认你的脚本有效。
在您的示例中,您已经被检索到访问令牌。我认为,当访问令牌可以用于使用Youtube数据API时,在这种情况下,脚本不需要使用API密钥即可工作。
参考资料:
https://stackoverflow.com/questions/60759454
复制相似问题