1

I have this piece of code to extract some metrics about my YouTube channel and create a pandas dataframe from them.

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
import json

SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']
API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'client_secrets.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()
  with open('data.json', 'w') as fp:
    json.dump(response, fp)

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='2014-01-01',
      endDate='2019-02-26',
      metrics='averageViewDuration,views,likes,dislikes,subscribersGained,subscribersLost',
      dimensions='day',
      sort='day',
      filters = 'country==US'
  )

## Now, convert the json to dataframe

import json
import pandas as pd

with open('data.json') as json_data:
    d = json.load(json_data)
colnames = [d['columnHeaders'][i]['name'] for i in range(0,len(d['columnHeaders']))]

Results = pd.DataFrame(d['rows'],columns  = colnames)
Results.to_csv("Youtube_data.csv")

By running this code, a windows opens and asks me to login into youtube and then provide me the authorization code. Entering this authorization code finishes the running of above python program. However, you should repeat this authorization process each time you are running this program.

Is there anyway to bypass this repeated authorization such that this process can be automated?

Mgorji
  • 81
  • 2
  • 8
  • 1
    Please check how [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/OAuth2) works. Remember that the application uses the token to access a Google API. When the token expires, the application repeats the process. – Jessica Rodriguez Mar 01 '19 at 10:38
  • Please replace "impressions" in the question with "metrics". "Impressions" is actually not one of the metrics that you are downloading. – Paul Jun 25 '20 at 16:50

1 Answers1

0

You need to use the oauth2client.file.Storage class to store and retrieves the credentials object as (badly) explained here: https://developers.google.com/api-client-library/python/guide/aaa_oauth

You will need to modify your get_service function with something like this:

from oauth2client import client, file

def get_service():
  flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, SCOPES)
  storage = file.Storage(API_SERVICE_NAME + '.dat')
  credentials = storage.get()

  http = credentials.authorize(http=httplib2.Http())

  service = build(API_SERVICE_NAME, API_VERSION, http=http)

  return service

Hope this helps

Giacomo
  • 1,796
  • 1
  • 24
  • 35