Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Created October 23, 2024 18:19
Show Gist options
  • Save JayGoldberg/7b0b80111bc3a5472213847bd6176728 to your computer and use it in GitHub Desktop.
Save JayGoldberg/7b0b80111bc3a5472213847bd6176728 to your computer and use it in GitHub Desktop.
Accessing youtubeanalytics.googleapis.com API using python
import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE='ytsecret.json'
SCOPES = ["https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/youtube.readonly"]
def get_service():
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_local_server(port=0)
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 NOTleave this option enabled when running in production.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
youtubeAnalytics = get_service()
execute_api_request(
youtubeAnalytics.reports().query,
ids='channel==<channel_id>',
startDate='2024-08-01',
endDate='2024-10-08',
metrics='estimatedMinutesWatched,views,likes,subscribersGained',
dimensions='day',
sort='day'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment