Steps
- Create new GCP project.
- From
Navigation Menu
findAPIs & Services
- Click
Enable APIs & Services
then click+ ENABLE APIS & SERVICES
- Search
Google Analytic
and clickEnable
- From
Navigation Menu
findIAM & Admin
thenService Accounts
- Click
+ CREATE SERVICE ACCOUNT
- In
Service account details
section, enterService account name
andService account ID *
, clickDone
- Go to this service account and find
KEYS
tab. ADD KEY
andCreate new key
, selectjson
- After downloaded, put it in the same path as your project.
- Use code below
Install package
pip install google-analytics-data
Python sample code:
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "<your-key-file-name>.json"
def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="city")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2020-03-31", end_date="today")],
)
response = client.run_report(request)
print("Report result:")
for row in response.rows:
print(row.dimension_values[0].value, row.metric_values[0].value)
sample_run_report(property_id="<your-ga4-property-id>")
Output will be like
(test) ycy@YCY-Mac demo % python ga.py
Report result:
(not set) 93
Zhongli District 10
Changhua City 2
Liverpool 2
Tamsui District 2
Taoyuan District 2
Zhunan Township 2
Bade District 1
Ballwin 1
Donggang Township 1
Douliu City 1
Durham 1
Manchester 1
Miaoli City 1
Saarbrucken 1
Shoufeng Township 1
Yilan City 1
Zhubei City 1
Reference
https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries