Skip to content

Commit c6a4411

Browse files
author
ruslanbergenov
committed
feat: run report (Adswerve example)
0 parents  commit c6a4411

File tree

5 files changed

+136
-0
lines changed

5 files changed

+136
-0
lines changed

.idea/.gitignore

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/GA_Reporting_API_Demos.iml

+10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

hello_analytics.py

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#TODO: repo
2+
#TODO: query segment
3+
#TODO: ga4
4+
#TODO: (optional: more complex example?)
5+
6+
""""Hello Analytics Reporting API V4.
7+
credit: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py"""
8+
9+
from apiclient.discovery import build
10+
from oauth2client.service_account import ServiceAccountCredentials
11+
import os
12+
print(os.getcwd())
13+
file_path = os.path.normpath(
14+
os.path.join(os.path.dirname(__file__), "sandbox", "adswerve-ts-content-marketing-sa.json"))
15+
16+
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
17+
KEY_FILE_LOCATION = file_path
18+
VIEW_ID = '146223021'
19+
20+
21+
def initialize_analyticsreporting():
22+
"""Initializes an Analytics Reporting API V4 service object.
23+
24+
Returns:
25+
An authorized Analytics Reporting API V4 service object.
26+
"""
27+
credentials = ServiceAccountCredentials.from_json_keyfile_name(
28+
KEY_FILE_LOCATION, SCOPES)
29+
30+
# Build the service object.
31+
analytics = build('analyticsreporting', 'v4', credentials=credentials)
32+
33+
return analytics
34+
35+
# Google's example
36+
# def get_report(analytics):
37+
# """Queries the Analytics Reporting API V4.
38+
#
39+
# Args:
40+
# analytics: An authorized Analytics Reporting API V4 service object.
41+
# Returns:
42+
# The Analytics Reporting API V4 response.
43+
# """
44+
# return analytics.reports().batchGet(
45+
# body={
46+
# 'reportRequests': [
47+
# {
48+
# 'viewId': VIEW_ID,
49+
# 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
50+
# 'metrics': [{'expression': 'ga:sessions'}],
51+
# 'dimensions': [{'name': 'ga:country'}]
52+
# }]
53+
# }
54+
# ).execute()
55+
56+
# our example
57+
def get_report(analytics):
58+
"""Queries the Analytics Reporting API V4.
59+
60+
Args:
61+
analytics: An authorized Analytics Reporting API V4 service object.
62+
Returns:
63+
The Analytics Reporting API V4 response.
64+
"""
65+
return analytics.reports().batchGet(
66+
body={
67+
'reportRequests': [
68+
{
69+
'viewId': VIEW_ID,
70+
'dateRanges': [{'startDate': '2022-09-16', 'endDate': '2022-09-22'}],
71+
'metrics': [{'expression': 'ga:pageviews'},{'expression': 'ga:uniquePageviews'}],
72+
'dimensions': [{'name': 'ga:pageTitle'}],
73+
"orderBys": [
74+
{
75+
"orderType": "VALUE",
76+
"sortOrder": "DESCENDING",
77+
"fieldName": "ga:pageviews"
78+
}
79+
]
80+
}]
81+
}
82+
).execute()
83+
84+
# https://stackoverflow.com/questions/47203801/google-analytics-reporting-api-v4-sort-results
85+
86+
def print_response(response):
87+
"""Parses and prints the Analytics Reporting API V4 response.
88+
89+
Args:
90+
response: An Analytics Reporting API V4 response.
91+
"""
92+
for report in response.get('reports', []):
93+
columnHeader = report.get('columnHeader', {})
94+
dimensionHeaders = columnHeader.get('dimensions', [])
95+
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
96+
97+
for row in report.get('data', {}).get('rows', []):
98+
dimensions = row.get('dimensions', [])
99+
dateRangeValues = row.get('metrics', [])
100+
101+
for header, dimension in zip(dimensionHeaders, dimensions):
102+
print(header + ': ', dimension)
103+
104+
for i, values in enumerate(dateRangeValues):
105+
print('Date range:', str(i))
106+
for metricHeader, value in zip(metricHeaders, values.get('values')):
107+
print(metricHeader.get('name') + ':', value)
108+
print("\n")
109+
def main():
110+
analytics = initialize_analyticsreporting()
111+
response = get_report(analytics)
112+
print_response(response)
113+
114+
if __name__ == '__main__':
115+
main()
116+

requirements.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
google-api-python-client
2+
oauth2client

sandbox/.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Ignore everything in this directory
2+
*
3+
# Except this file
4+
!.gitignore

0 commit comments

Comments
 (0)