5

I want to retrieve monetization data from a friend's YouTube channel. I've used the python code below to get the authentication credentials from him, which I then saved to a JSON file. In that process, he has to click a link and send me the key. I want to avoid that by saving the credentials data. I think I have done that, but how do I load it now?

import json
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', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']
API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'client_secret_dota2rapier_youtube_analytics_api.json'
CLIENT_CREDENTIALS_FILE = 'credentials.json'
root = 'C:\\test\\'
os.chdir(root)


def get_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()

  #SAVING CREDENTIALS DATA
  creds_data = {
      'token': credentials.token,
      'refresh_token': credentials.refresh_token,
      'token_uri': credentials.token_uri,
      'client_id': credentials.client_id,
      'client_secret': credentials.client_secret,
      'scopes': credentials.scopes
  }
  save = True
  if save:
      del creds_data['token']
      with open('credentials.json', 'w') as outfile:
          json.dump(creds_data, outfile)

  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==UC0NM4tKT5s9szqnK3jp6dEw',
      startDate='2018-12-20',
      endDate='2018-12-30',
      metrics='views,likes,estimatedRevenue',
      dimensions='day',
      sort='day'
  )
Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
Anders Lunde
  • 121
  • 1
  • 11
  • Rather than build your own JSON the `Credentials` instance provides a `to_json()` which I believe does the same thing: https://google-auth.readthedocs.io/en/master/reference/google.oauth2.credentials.html?highlight=to_json#google.oauth2.credentials.Credentials.to_json – Neil C. Obremski Jun 11 '21 at 20:18

3 Answers3

4

Solved it myself. I just needed to create the credentials object with this code:

credentials = google.oauth2.credentials.Credentials.from_authorized_user_file(CLIENT_CREDENTIALS_FILE)
Anders Lunde
  • 121
  • 1
  • 11
  • Check that you can refresh the access token using the saved refresh token. – John Hanley Jan 02 '19 at 20:55
  • How do I check that? Anyway, I used the credential many times now to perform different queries successfully to the API. Do you mean it might expire soon? – Anders Lunde Jan 02 '19 at 23:34
  • Yes, credentials expire. Usually after 3600 seconds. I am not 100% sure, but I think that you will have a problem refreshing the Access Token as your callback url will be different - e.g. it must match what is in the Google Console for the Client ID / Client Secret. I am interested in finding out the exact answer for security reasons and to further my OAuth experience. – John Hanley Jan 03 '19 at 00:00
  • Tested it again today, ca 20 hours later. Still works – Anders Lunde Jan 03 '19 at 16:23
  • Thank you for coming back and answering your own question @AndersLunde - came in handy for a similar situation with Youtube Data API. Could not find this anywhere in the documentation, has been searching for hours. – Aswin Kumar Jun 05 '19 at 09:31
1

I had the same problem with the Google calendar's generated token as a JSON file for use in the next run. Here's what I've done:

import ast
import json

from google.oauth2.credentials import Credentials

if os.path.exists("token.json"):
    with open("token.json", "r") as token:
        creds = Credentials.from_authorized_user_info(
            ast.literal_eval(json.load(open("token.json")))
        )
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
0

I would just open the file and dump the json into a dictionary.

def read_config(config):
    # config is the name/path to your config file
    with open(config, 'r') as infile:
          config = json.load(infile)

    return(config)


config = read_config("yourfile.json")
id, secret = config["client_id"], config['client_secret"]
mikeg
  • 444
  • 3
  • 13
  • This just returns some of the content of the json file. I need to create a credentials object. – Anders Lunde Jan 02 '19 at 19:28
  • Yes, and that is what you had asked for "I want to avoid that by saving the credentials data. I think I have done that, but how do I load it now?", you made no mention of a credentials object. I am glad to see that you found the solution on how to create the object :). – mikeg Jan 02 '19 at 21:17