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

Why am I getting "Request is missing required authentication credential" when making POST request to YouTube API v3 with Python Requests module?

我正在使用 Python 下载 YouTube 评论,方法是使用请求模块向

发出 POST 请求

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

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

{'error': {'code': 401, '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.', 'errors': [{'message': 'Login Required.', 'domain': 'global', 'reason': 'required', 'location': 'Authorization', 'locationType': 'header'}], 'status': 'UNAUTHENTICATED'}}.

据我所知,这个(和 link)是说我需要一个 OAuth 2 令牌,但我觉得这不适用于我正在尝试的那种功能执行。

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

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 endpoint, and not CommentThreads.list

这解释了为什么 API 抱怨没有收到 OAuth 令牌,因为 CommentThreads.insert 确实需要这种 authorization

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

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

因此,要修复您的代码,您必须拥有类似的东西:

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

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