Skip to content

Commit

Permalink
Use beta data reporting API
Browse files Browse the repository at this point in the history
  • Loading branch information
kand198 committed Sep 21, 2022
1 parent c7c0b15 commit 57a28dd
Showing 1 changed file with 55 additions and 74 deletions.
129 changes: 55 additions & 74 deletions scripts/HelloAnalytics.py
Original file line number Diff line number Diff line change
@@ -1,78 +1,59 @@
"""Hello Analytics Reporting API V4."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'key.json'
VIEW_ID = '3535025389'


def initialize_analyticsreporting():
"""Initializes an Analytics Reporting API V4 service object.
Returns:
An authorized Analytics Reporting API V4 service object.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)

# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)

return analytics


def get_report(analytics):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
).execute()


def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response.
Args:
response: An Analytics Reporting API V4 response.
"""
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

for row in report.get('data', {}).get('rows', []):
dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])

for header, dimension in zip(dimensionHeaders, dimensions):
print(header + ': ', dimension)

for i, values in enumerate(dateRangeValues):
print('Date range:', str(i))
for metricHeader, value in zip(metricHeaders, values.get('values')):
print(metricHeader.get('name') + ':', value)

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import *
from google.oauth2 import service_account


def sample_run_report(client, property_id):
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="customUser:user_group")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2022-09-18", end_date="today")],
)
response = client.run_report(request)

print("Report result:")
for dimension_header in response.dimension_headers:
print(dimension_header.name, end="\t")

for metric_header in response.metric_headers:
print(metric_header.name, end="\n")

for row in response.rows:
rowString = ''
for dimension in row.dimension_values:
rowString += f"{dimension.value}\t\t"
for metric in row.metric_values:
rowString += f"{metric.value}\t\t"
print(rowString)

def sample_run_relatime_report(client: BetaAnalyticsDataClient, property_id):
request = RunRealtimeReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="customUser:user_group")],
metrics=[Metric(name="activeUsers")],
)
response: RunRealtimeReportResponse = client.run_realtime_report(request)

print("Realtime report result:")
for dimension_header in response.dimension_headers:
print(dimension_header.name, end="\t")

for metric_header in response.metric_headers:
print(metric_header.name, end="\t\n")

for row in response.rows:
rowString = ''
for dimension in row.dimension_values:
rowString += f"{dimension.value}\t"
for metric in row.metric_values:
rowString += f"{metric.value}\t"
print(rowString)

def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)

credentials = service_account.Credentials.from_service_account_file(".\pedagogic-ide-a137fcb189d5.json")
client = BetaAnalyticsDataClient(credentials=credentials)
# sample_run_report(client, "313384509")
sample_run_relatime_report(client, "313384509")
if __name__ == '__main__':
main()

0 comments on commit 57a28dd

Please sign in to comment.