Google's youtube Analytics API is Oauth2 based only. I am using the below test script to see if I can gain access:
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 = 'client_secret.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'
)
my problem is that this script requres me to open a browser, set a link, login, then get a token cable.
Is there ANY way to do this in a "headless" mode? I need to pull these APIs for machine-to-machine transfer.
Thanks!
Do it once, then save the credentials object returned by credentials = flow.run_console() to either a database or a file. This contains a "refresh token" which can be used in subsequent api calls, meaning you can skip the flow.run_console step, and just use the saved credentials in a build(API_SERVICE_NAME, API_VERSION, credentials = credentials) call.
There's a note about this in the docs here:
https://developers.google.com/youtube/reporting/guides/authorization/installed-apps#exchange-authorization-code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With