I am working on an application to pull the YouTube metrics using the YouTube analytics API. This is the first time I am working with google auth flow to authenticate my app so that it can silently pull the report.
I am following the below Google published article to work out the same: https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps
While following this article I am unable to figure out how to redirect the user to the auth_uri and obtain the auth_code.
Below is the code I have written for the auth flow so far:
API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'C:/Users/Tushar/Documents/Serato_Video_Intelligence/client_secret_youtube.json'
def get_service():
global auth_code
global auth_uri
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS_FILE,
scope='https://www.googleapis.com/auth/yt-analytics.readonly',
redirect_uri = "http://localhost:8080")
flow.params['access_type'] = 'offline'
flow.params['include_granted_scopes'] = True
auth_uri = flow.step1_get_authorize_url()
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
return build(API_SERVICE_NAME, API_VERSION, http=http_auth)
def execute_api_request(client_library_function, **kwargs):
response = client_library_function(
**kwargs
).execute()
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==XXXXXXXXXXXXXX',
startDate='2019-04-12',
endDate='2019-08-13',
filters= 'video==XXXXXXXXXXXXXX',
metrics='audienceWatchRatio,relativeRetentionPerformance',
dimensions='elapsedVideoTimeRatio'
)
When I run this code I get an error
File "C:\Users\Tushar\Documents\Serato_Video_Intelligence\youtube_auth_testing.py", line 65, in <module>
youtubeAnalytics = get_service()
File "C:\Users\Tushar\Documents\Serato_Video_Intelligence\youtube_auth_testing.py", line 40, in get_service
credentials = flow.step2_exchange(auth_code)
NameError: name 'auth_code' is not defined
I have gone through the articles on Stack Overflow and Google but have been unable to figure out what to do. I certainly know there are couple of steps that I am missing but I am unable to resolve it.