Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active April 11, 2023 06:00
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 gh640/09081268435d053780e58dc3be61914f to your computer and use it in GitHub Desktop.
Save gh640/09081268435d053780e58dc3be61914f to your computer and use it in GitHub Desktop.
Sample: Get pages with most sessions from GA4 with Python and Google Analytics Data API v1
"""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,
)
# Changes these values:
CREDENTIALS_PATH = Path(__file__).resolve().parent / "credentials.json"
PROPERTY_ID = "XXX"
MAX_ROWS = 20
def main():
client = BetaAnalyticsDataClient.from_service_account_file(CREDENTIALS_PATH)
request = build_report_request(PROPERTY_ID, MAX_ROWS)
response = client.run_report(request)
print("Report result:")
show_report(response)
def build_report_request(property_id: str, size: int):
return RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name="pagePath"), Dimension(name="pageTitle")],
metrics=[Metric(name="sessions")],
date_ranges=[DateRange(start_date="30daysAgo", end_date="today")],
order_bys=[
OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True),
],
limit=size,
)
def show_report(response):
dimension_headers = response.dimension_headers
metric_headers = response.metric_headers
for row in response.rows:
dim_map = _map_of_values(dimension_headers, row.dimension_values)
met_map = _map_of_values(metric_headers, row.metric_values)
print(dim_map)
print(met_map)
def _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 Apr 11, 2023

Prerequisites

  • Python 3.11
  • google-analytics-data ^0.16.0
  • service account key file (put in the same directory as credentials.json)

Usage

Install google-analytics-data

python -m pip install google-analytics-data

Change the following constants in the script:

  • PROPERTY_ID
  • CREDENTIALS_PATH (if necessary)
  • MAX_ROWS

Run the script:

python sample-ga-data-api.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment