본문 바로가기
Programming/Python

[Google Analytics Data API] Call Google Analytics Data API with Python

by guru_k 2022. 5. 9.
728x90
반응형

아래 페이지를 통해 Google Analytics Data API V1 을 활성화 합니다.

활성화 이후 생성된 credentials.json을 잘 저장해둡니다.

credentials.json에 생성된 아래와 같은 client_email 계정을 GA4 property에 접근할 수 있도록 추가 해줍니다.

ex) quickstart@PROJECT-ID.iam.gserviceaccount.com

 

Admin -> Account Access Management로 이동 합니다.

Add users 를 선택한다음 credentials.json에 있는 client_email 계정을 추가해줍니다.

이때 Permission은 Analyst 로 선택 해줍니다.

인증 설정을 위해 위에서 다운로드 받은 credentials.json의 경로를 env로 지정해줍니다.

$ export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/credentials.json"

호출하기 위한 python 코드를 아래와 같이 생성합니다.

# ga.py

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange
from google.analytics.data_v1beta.types import Dimension
from google.analytics.data_v1beta.types import Metric
from google.analytics.data_v1beta.types import RunReportRequest


def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a simple report on a Google Analytics 4 property."""
    # TODO(developer): Uncomment this variable and replace with your
    #  Google Analytics 4 property ID before running the sample.
    # property_id = "YOUR-GA4-PROPERTY-ID"

    # Using a default constructor instructs the client to use the credentials
    # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    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:", response)
    for row in response.rows:
        print(row.dimension_values[0].value, row.metric_values[0].value)
        
sample_run_report()

python을 실행하여 호출합니다.

$ python3 ga.py
Report result: metadata {
  currency_code: "USD"
  time_zone: "Asia/Seoul"
}
kind: "analyticsData#runReport"
728x90
반응형

댓글