Describes how to get the number of visits to each page using ReportingAPI + Cloud Functions. Reporting API v4 (google-api-python-client) is used to acquire data from Google Analytics.
google-api-python-client: 1.12.2 oauth2client: 4.1.3
Enable Reporting API v4 from Google API Console . At this time, download the private key and make a note of the email address of the service account.
[email protected]
Add the previous email address from Google Analytics [Administration]> [Show User Management]> [Add User] To do.
Create a function from GCP's Cloud Functions, paste the following source, and you're done
main.py
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'Json file path'
VIEW_ID = 'VIEW_ID'
def initialize_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:uniquePageviews'}],
'dimensions': [{'name': 'ga:pagePath'}]
}]
}
).execute()
def print_response(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 i, values in enumerate(dateRangeValues):
for dimension, value in zip(dimensions, values.get('values')):
print(dimension + ':' + value)
def main(event, context):
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)
requirements.txt
google-api-python-client==1.12.2
oauth2client==4.1.3
I was new to Python, GCP, and Analytics, so I learned a lot. This time I wanted a ranking function for my blog, so I made it, but how much does the price differ from counting the number of accesses to the Fire Store?: Thinking: It seems better to acquire knowledge of Analytics before doing Reporting API (laugh)
Recommended Posts