[PYTHON] Get the number of visits to each page with ReportingAPI + Cloud Functions

Purpose

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.

environment

google-api-python-client: 1.12.2 oauth2client: 4.1.3

flow

    1. Google API Console settings
  1. Google Analytics settings
    1. Output Analytics data

1. 1. Google API Console settings

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]

2. Google Analytics settings

Add the previous email address from Google Analytics [Administration]> [Show User Management]> [Add User] To do.

3. 3. Output Analytics data

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

Impressions

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

Get the number of visits to each page with ReportingAPI + Cloud Functions
Get the source of the page to load infinitely with python.
Try to get the contents of Word with Golang
Get the number of digits
How to count the number of occurrences of each element in the list in Python with weight
Get the number of occurrences for each element in the list
Get the number of views of Qiita
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
Get the number of Youtube subscribers
Get the number of PVs of Qiita articles you posted with API
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
PhytoMine-I tried to get the genetic information of plants with Python
Count the number of characters with echo
Get the number of searches with a regular expression. SeleniumBasic VBA Python
I tried to get the authentication code of Qiita API with Python.
Convert the spreadsheet to CSV and upload it to Cloud Storage with Cloud Functions
Get the number of articles accessed and likes with Qiita API + Python
I tried to get the movie information of TMDb API with Python
The easiest way to get started with Django
Convert data with shape (number of data, 1) to (number of data,) with numpy.
Calculate the total number of combinations with python
Use twitter API to get the number of tweets related to a certain keyword
Note: How to get the last day of the month with python (added the first day of the month)
[Verification] Try to align the point cloud with the optimization function of pytorch Part 1
To get the path of the currently running python.exe
I wanted to know the number of lines in multiple files, so I tried to get it with a command
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
How to identify the element with the smallest number of characters in a Python list?
Get information equivalent to the Network tab of Chrome developer tools with Python + Selenium
An easy way to pad the number with zeros depending on the number of digits [Python]
How to get started with Visual Studio Online ~ The end of the environment construction era ~
[For beginners] Web scraping with Python "Access the URL in the page to get the contents"
python beginners tried to predict the number of criminals
How to know the port number of the xinetd service
Add information to the bottom of the figure with Matplotlib
Try to estimate the number of likes on Twitter
Get to know the feelings of gradient boosting trees
Predict the number of people infected with COVID-19 with Prophet
Get the size (number of elements) of UnionFind in Python
Manage the package version number of requirements.txt with pip-tools
Date the name of the decomposed PDF for each page
Get the operation status of JR West with Python
Script to get the expiration date of the SSL certificate
[Python] Get the number of views of all posted articles
Summary of how to share state with multiple functions
I tried to display the point cloud data DB of Shizuoka prefecture with Vue + Leaflet
[Introduction to SIR model] Predict the end time of each country with COVID-19 data fitting ♬
[Introduction to logarithmic graph] Predict the end time of each country from the logarithmic graph of infection number data ♬
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
How to find the optimal number of clusters in k-means
Try to get the function list of Python> os package
I tried to get the location information of Odakyu Bus
I tried to find the average of the sequence with TensorFlow
Cloud Functions to resize images using OpenCV with Cloud Storage triggers
Minimum knowledge to get started with the Python logging module
Get the package version to register with PyPI from Git
Get the number of specific elements in a python list