楊育晟(Peter Yang)

嗨, 我叫育晟, 部落格文章主題包含了程式設計、財務金融及投資...等等,內容多是記錄一些學習的過程和心得,任何想法都歡迎留言一起討論。



Email: ycy.tai@gmail.com
LinkedIn: Peter Yang
Github: ycytai

How to use ga api(Google Analytic)

Steps

  1. Create new GCP project.
  2. From Navigation Menu find APIs & Services
  3. Click Enable APIs & Services then click + ENABLE APIS & SERVICES
  4. Search Google Analytic and click Enable
  5. From Navigation Menu find IAM & Admin then Service Accounts
  6. Click + CREATE SERVICE ACCOUNT
  7. In Service account details section, enter Service account name and Service account ID *, click Done
  8. Go to this service account and find KEYS tab.
  9. ADD KEY and Create new key, select json
  10. After downloaded, put it in the same path as your project.
  11. 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

Tags:
# python
# javascript
# google
# google analytic
# memo