Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am downloading YouTube comments with Python by making POST requests with the Requests module to

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

However, even though I am supplying an API key, I am getting the following error message:

{'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'}}.

From what I can gather, this (and the link) is saying that I need an OAuth 2 token, but I don't feel like that is applicable to the kind of function I am trying to carry out.

Here is the code I am using to make the request:

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()

Can anyone tell me why I am getting this error message?

like image 441
Charlie Armstead Avatar asked Feb 03 '26 10:02

Charlie Armstead


1 Answers

(Sorry, Charlie, I should have noticed the problem earlier.)

The problem with your code is as follows: since you're invoking the HTTP POST method on the URL:

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

it means that you really are invoking the CommentThreads.insert API endpoint, and not CommentThreads.list.

This explains why the API complains about not receiving an OAuth token, since CommentThreads.insert do require such kind of authorization.

Do notice that the two endpoints have the same URL, yet what differentiates one from the other is the HTTP method that invoked each:

  • GET for CommentThreads.list, and
  • POST for CommentThreads.insert.

Therefore, to fix your code you'll have to have something like:

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

Note also that passing params is simply OK (it's not necessary to pass the request's parameters to data).

like image 82
stvar Avatar answered Feb 05 '26 23:02

stvar