Search code examples
pythongoogle-apiyoutubeyoutube-apigoogle-api-python-client

Python YouTube Reporting API Authentication


I've sorted through many threads on this topic but most seem outdated.

I am trying to call the YouTube Reporting API with this script

However I keep getting an error:

  • When using 'Desktop Application' OAuth, I get:

Error 400: invalid_request, The out-of-band (OOB) flow has been blocked in order to keep users secure.

  • When using 'Web Application' OAuth, I get:

Error 400: redirect_uri_mismatch, The redirect URI in the request, urn:ietf:wg:oauth:2.0:oob, can only be used by a Client ID for native application. It is not allowed for the WEB client type.

I am just still testing my code and been running out of jupyter notebook and Visual Studio Code. Same errors on both.

I am still a little confused as to which one I should be using, but adding redirect URI's for my localhost is not working, not sure how to proceed.

EDIT: I am using the below code sample directly from YouTube Documentation:

import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']

API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'CREDENTIALS.json'
def get_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

def execute_api_request(client_library_function, **kwargs):
  response = client_library_function(
    **kwargs
  ).execute()

  print(response)

if __name__ == '__main__':
  # Disable OAuthlib's HTTPs verification when running locally.
  # *DO NOT* leave this option enabled when running in production.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  youtubeAnalytics = get_service()
  execute_api_request(
      youtubeAnalytics.reports().query,
      ids='channel==MINE',
      startDate='2017-01-01',
      endDate='2017-12-31',
      metrics='estimatedMinutesWatched,views,likes,subscribersGained',
      dimensions='day',
      sort='day'
  )

Like mentioned I have http://localhost:8888, http://localhost:8888/oauth2callback etc. In my json file + in Google Console.

'urn:ietf:wg:oauth:2.0:oob' is not in my code/file/google console at any point. I also have the .../auth/yt-analytics.readonly defined in my OAuth consent screen settings.

Really not sure what I have missed out on.


Solution

  • The script is meant to be used with 'Desktop Application' type of credentials.

    YouTube's documentation is outdated, the below needs to be changed for it to work:

    credentials = flow.run_console()
    

    changed to

    credentials = flow.run_local_server()