Skip to content

Commit 0726330

Browse files
Add .py sample for calling YT Analytics API (v2)
1 parent cdf1f87 commit 0726330

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

python/yt_analytics_v2.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import os
4+
import google.oauth2.credentials
5+
import google_auth_oauthlib.flow
6+
from googleapiclient.discovery import build
7+
from googleapiclient.errors import HttpError
8+
from google_auth_oauthlib.flow import InstalledAppFlow
9+
10+
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']
11+
12+
API_SERVICE_NAME = 'youtubeAnalytics'
13+
API_VERSION = 'v2'
14+
CLIENT_SECRETS_FILE = 'YOUR_CLIENT_SECRET_FILE.json'
15+
def get_service():
16+
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
17+
credentials = flow.run_console()
18+
return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
19+
20+
def execute_api_request(client_library_function, **kwargs):
21+
response = client_library_function(
22+
**kwargs
23+
).execute()
24+
25+
print(response)
26+
27+
if __name__ == '__main__':
28+
# Disable OAuthlib's HTTPs verification when running locally.
29+
# *DO NOT* leave this option enabled when running in production.
30+
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
31+
32+
youtubeAnalytics = get_service()
33+
execute_api_request(
34+
youtubeAnalytics.reports().query,
35+
ids='channel==MINE',
36+
startDate='2017-01-01',
37+
endDate='2017-12-31',
38+
metrics='estimatedMinutesWatched,views,likes,subscribersGained'
39+
dimensions='day',
40+
sort='day'
41+
)

0 commit comments

Comments
 (0)