Sample: Getting session data of GA4 with Python and `google-analytics-data`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""A sample to get sessions with Python and Google Analytics Data API v1. | |
with: google-analytics-data = "^0.16.0" | |
""" | |
from pathlib import Path | |
from google.analytics.data_v1beta import BetaAnalyticsDataClient | |
from google.analytics.data_v1beta.types import ( | |
DateRange, | |
Dimension, | |
Metric, | |
RunReportRequest, | |
OrderBy, | |
) | |
# Change theese values: | |
CREDENTIALS_PATH = Path(__file__).resolve().parent / "credentials.json" | |
PROPERTY_ID = "123456789" | |
def main(): | |
sample_run_report(CREDENTIALS_PATH, PROPERTY_ID, 20) | |
def sample_run_report(credentials_path, property_id: str, size: int): | |
"""Runs a simple report on a Google Analytics 4 property.""" | |
client = BetaAnalyticsDataClient.from_service_account_file(credentials_path) | |
request = RunReportRequest( | |
property=f"properties/{property_id}", | |
dimensions=[Dimension(name="pagePath"), Dimension(name="pageTitle")], | |
metrics=[Metric(name="sessions")], | |
date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], | |
order_bys=[ | |
OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True) | |
], | |
limit=size, | |
) | |
response = client.run_report(request) | |
print("Report result:") | |
dimension_headers = response.dimension_headers | |
metric_headers = response.metric_headers | |
for row in response.rows: | |
dim_map = _make_map_of_values(dimension_headers, row.dimension_values) | |
met_map = _make_map_of_values(metric_headers, row.metric_values) | |
print(dim_map, met_map) | |
def _make_map_of_values(headers, values) -> dict: | |
return {k: v for k, v in zip((x.name for x in headers), (x.value for x in values))} | |
if __name__ == "__main__": | |
main() |
One needs to install PyPI package google-analytics-data
before trying this script:
python -m pip install google-analytics-data
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: