|
| 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 | + |
0 commit comments