Skip to content

Instantly share code, notes, and snippets.

@tpai
Last active January 9, 2024 10:20
Show Gist options
  • Save tpai/e69f831eee591b43df1d86c7258cc166 to your computer and use it in GitHub Desktop.
Save tpai/e69f831eee591b43df1d86c7258cc166 to your computer and use it in GitHub Desktop.
A simple Python script for calling GA4 API
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)
#!/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