Last active
April 11, 2023 06:00
-
-
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
This file contains hidden or 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, | |
) | |
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prerequisites
google-analytics-data
^0.16.0
credentials.json
)Usage
Install
google-analytics-data
Change the following constants in the script:
PROPERTY_ID
CREDENTIALS_PATH
(if necessary)MAX_ROWS
Run the script: