Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created March 13, 2023 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuriyanto48/818a4b134331025fdf228543817c6619 to your computer and use it in GitHub Desktop.
Save wuriyanto48/818a4b134331025fdf228543817c6619 to your computer and use it in GitHub Desktop.
Python: Fetch Google Analytic 4 data with google-analytics data module
import os
import json
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def fetch_report(client, property_id):
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[
Dimension(name="city"),
Dimension(name="mobileDeviceBranding"),
Dimension(name="platform"),
Dimension(name="operatingSystem"),
Dimension(name="mobileDeviceModel"),
],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2023-01-01", end_date="today")],
)
response = client.run_report(request)
print("Report result:")
for row in response.rows:
print(row.dimension_values)
print('-----------------')
if __name__ == "__main__":
PROPERTY_ID = '292104555'
credentials_path = os.path.join(BASE_DIR, 'credentials.json')
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials_path
client = BetaAnalyticsDataClient.from_service_account_json(credentials_path)
fetch_report(client, PROPERTY_ID)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment