Sagi Mann
Sagi Mann

Reputation: 3620

google.oauth2.credentials.Credentials fails with valid token

I'm trying to list my YouTube channels via Python 3.6, given (and this is important) an EXISTING access token and some valid API key. It works well with curl and returns a valid JSON response:

curl 'https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true&key=API_KEY' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer ACCESS_TOKEN'

response:

{
    "kind": "youtube#channelListResponse",
    "etag": "\"xxxxxxxxx\"",
    "pageInfo": {...},
    "items": [...]
}

If I remove the Authorization header, I get the expected error:

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

Now, I try to do the same with the Google Python library (because I need it for more complex operations and code control), but it doesn't work. I get the same error as if I did not pass any access token. Any ideas what I'm doing wrong? Here is my Python code (note the access token is given to the code, I MUST use it as-is):

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

I run it like so:

python3 test.py --api_key MY_API_KEY --access_token MY_ACCESS_TOKEN

Upvotes: 1

Views: 435

Answers (1)

Tanaike
Tanaike

Reputation: 201683

I think that your script works. Actually, in my environment, I could confirm that your script worked.

In your case, you have already been retrieved the access token. I think that when the access token can be used for using Youtube Data API, in this case, the script works without using the API key.

Reference:

Upvotes: 1

Related Questions