Automation Help: Google Analytics Data API (GA4) with Python [Extensive Guide]
Google Cloud Platform μ½μ
λ‘ μ΄λνμ¬ Google Analytics Data API
λ₯Ό νμ±ννλ κ²λΆν° μμIAM λ° μλΉμ€
λ₯Ό ν΄λ¦ν λ€μ μλΉμ€ κ³μ μ ν΄λ¦νμ¬ μλΉμ€ κ³μ μ€μ μΌλ‘ μ΄λCREATE SERVICE ACCOUNT
λ₯Ό ν΄λ¦νμ¬ νμν μλΉμ€ κ³μ μμ±μ μμμλ£
λ₯Ό ν΄λ¦ν€ κ΄λ¦¬
λ₯Ό ν΄λ¦ν€ μΆκ°
λ₯Ό ν΄λ¦νκ³ μ ν€
λ₯Ό ν΄λ¦CREATE
λ₯Ό ν΄λ¦μμ±
μΌλ‘ μ΄λνμ¬ μλΉμ€ κ³μ μ μ¬μ©μ κ΄λ¦¬μ μΆκ°νλ μμ
νμκ΄λ¦¬μ μ€μ
β μμ± μ¬μ©μ κ΄λ¦¬
λ₯Ό ν΄λ¦μ½κΈ° λ° λΆμ
κΆνμ΄ μΆ©λΆν΄μΌ ν¨pip
λͺ
λ Ήμ μ¬μ©νμ¬ Google Analytics Data API(GA4)
λ₯Ό μ€μΉpip install google-analytics-data
GOOGLE_APPLICATION_CREDENTIALS
λΌλ νκ²½ λ³μλ₯Ό μ€μ import os
# Set environment variables
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = service_account_file_path
PROPERTY_ID
λ₯Ό μμ± ID
λ‘ λ³κ²½μμ± ID
λ₯Ό μ°ΎμΌλ €λ©΄ Google μ λ리ν±μ€ κ΄λ¦¬μ μ€μ
μΌλ‘ μ΄λνμ¬ μμ± μ€μ
μΌλ‘ μ΄λ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):
"""Runs a simple report on a Google Analytics 4 property."""
# 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:")
for row in response.rows:
print(row.dimension_values[0].value, row.metric_values[0].value)
sample_run_report(PROPERTY_ID)
Pandas λΌμ΄λΈλ¬λ¦¬
μ¬μ© κ°λ₯CSV
λ‘ μ μ₯νλ €λ©΄ .to_csv
λ₯Ό μ¬μ©νκ³ Excel
μ κ²½μ° .to_excel
μ μ¬μ©import pandas as pd
def sample_run_report(property_id, export_path):
"""Runs a simple report on a Google Analytics 4 property."""
# 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)
output = []
print("Report result:")
for row in response.rows:
output.append({"City":row.dimension_values[0].value, "Active Users": row.metric_values[0].value})
df = pd.DataFrame(output)
df.to_csv(export_path)
sample_run_report(PROPERTY_ID, "export.csv")
df = pd.read_csv("export.csv")
df.head(5)