
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-dataGOOGLE_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)