- Enable Google Analytics Data API
- Create
ga4api
service account - Create key(credential) for the service account and save as JSON file
- Assign
ga4api@<project_id>.iam.gserviceaccount.com
as GA4 viewer - Run
./main.sh <ga4_property_id>
Last active
January 9, 2024 10:20
-
-
Save tpai/e69f831eee591b43df1d86c7258cc166 to your computer and use it in GitHub Desktop.
A simple Python script for calling GA4 API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from google.analytics.data_v1beta import BetaAnalyticsDataClient | |
from google.analytics.data_v1beta.types import ( | |
DateRange, | |
Dimension, | |
Filter, | |
FilterExpression, | |
Metric, | |
RunReportRequest, | |
) | |
def run_report(property_id="YOUR-GA4-PROPERTY-ID"): | |
client = BetaAnalyticsDataClient() | |
request = RunReportRequest( | |
property=f"properties/{property_id}", | |
dimensions=[Dimension(name="itemCategory"), Dimension(name="transactionId")], | |
metrics=[Metric(name="itemPurchaseQuantity"), Metric(name="itemRevenue")], | |
date_ranges=[DateRange(start_date="2024-01-01", end_date="today")], | |
dimension_filter=FilterExpression( | |
filter=Filter( | |
field_name="transactionId", | |
string_filter=Filter.StringFilter(match_type="CONTAINS",value="GA4_"), | |
) | |
), | |
) | |
response = client.run_report(request) | |
print("Report result:") | |
for row in response.rows: | |
print(row.dimension_values[0].value, row.dimension_values[1].value, row.metric_values[0].value, row.metric_values[1].value) | |
def main(argv): | |
run_report(argv[1]) | |
if __name__ == "__main__": | |
main(sys.argv) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
python3 -m venv ga4api | |
source ga4api/bin/activate | |
pip install google-analytics-data | |
# make sure your service account credential is ready | |
GOOGLE_APPLICATION_CREDENTIALS="$(pwd)/credentials.json" python main.py $1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment