Skip to content

Instantly share code, notes, and snippets.

@gh640
Created January 16, 2023 05:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gh640/9af94523bd0c1188fe35b64dcfb3e3ad to your computer and use it in GitHub Desktop.
Save gh640/9af94523bd0c1188fe35b64dcfb3e3ad to your computer and use it in GitHub Desktop.
Sample: Getting session data of GA4 with Python and `google-analytics-data`
"""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()
@gh640
Copy link
Author

gh640 commented Jan 16, 2023

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