python - 为什么我在使用 Python 请求模块向 YouTube API v3 发出 POST 请求时得到 "Request is missing required authentication credential"?

标签 python python-requests youtube-api youtube-data-api

我通过使用 Requests 模块发出 POST 请求来使用 Python 下载 YouTube 评论

https://www.googleapis.com/youtube/v3/commentThreads

但是,即使我提供了 API key ,我仍收到以下错误消息:

{'error': {'code': 401, 'message': '请求缺少必需的身份验证凭据。预期的 OAuth 2 访问 token 、登录 cookie 或其他有效的身份验证凭据。请参阅 https://developers.google.com/identity/sign-in/web/devconsole-project。', 'errors': [{'message': 'Login Required.', 'domain': 'global', ' reason': 'required', 'location': 'Authorization', 'locationType': 'header'}], 'status': 'UNAUTHENTICATED'}}.

据我所知,这个(和链接)是说我需要一个 OAuth 2 token ,但我觉得这不适用于我要执行的那种功能。

这是我用来发出请求的代码:

import requests

YOUTUBE_COMMENTS_URL = 'https://www.googleapis.com/youtube/v3/commentThreads'
params = {
            'part': 'snippet,replies',
            'maxResults': 100,
            'videoId': video_id,
            'textFormat': 'plainText',
            'key': ******
        }
        
headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
        }
data = requests.post(self.YOUTUBE_COMMENTS_URL, params=params, headers=headers)
results = data.json()

谁能告诉我为什么会收到此错误消息?

最佳答案

(抱歉,查理,我应该早点注意到这个问题。)

您的代码的问题如下:因为您在 URL 上调用 HTTP POST 方法:

https://www.googleapis.com/youtube/v3/commentThreads,

这意味着你真的在调用 CommentThreads.insert API 端点,而不是 CommentThreads.list .

这解释了为什么 API 提示没有收到 OAuth token ,因为 CommentThreads.insert 确实需要这种 authorization .

请注意,这两个端点具有相同的 URL,但它们之间的区别在于调用每个端点的 HTTP 方法:

  • GET对于 CommentThreads.list
  • POST对于 CommentThreads.insert

因此,要修复您的代码,您必须拥有如下内容:

data = requests.get(
    YOUTUBE_COMMENTS_URL,
    params = params,
    headers = headers
)

另请注意,传递 params 就可以了(没有必要将请求的参数传递给 data)。

关于python - 为什么我在使用 Python 请求模块向 YouTube API v3 发出 POST 请求时得到 "Request is missing required authentication credential"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64720038/

相关文章:

python - 检查属性是否可设置/可删除

python - AWS Lambda (python) 中的 Cassandra 数据库 session 重用

python - Python 中的高效协整检验

python - 有序的http请求参数

python - Django 单元测试和模拟请求模块

python - 使用 Python 请求将文件放入 S3

javascript - 在 Windows 8 应用程序中使用 Youtube Player API

javascript - 需要获取 YouTube 视频的可用字幕轨道列表

list - 是否可以从文本文件中制作YouTube列表?

python - 在python中让两个变量相互追踪