Sub topic 13
Pulling the same numbers with the Data API
The Pages and screens report and the Events report are both built from events. The GA4 Data API reads that same event data, so you can reproduce a report row by code. This is useful for scheduled exports, dashboards, and checking that a number in the interface means what you think it means.
This chapter assumes you can read the Pages and screens and Events reports, and that you know how an engaged session, engagement rate, and bounce rate are defined. It also assumes basic JSON and HTTP knowledge, and some familiarity with Python for the client example.
How a request maps to a report
A report in the interface is a table of dimensions (the row labels) and metrics (the numbers). A runReport request describes the same table: which date range, which dimensions, which metrics, and any filters, sorting, and row limit.
The method belongs to a property. You send a POST request to this address, replacing PROPERTY_ID with the numeric ID shown in Admin, under Property details:
https://analyticsdata.googleapis.com/v1beta/properties/PROPERTY_ID:runReportAuthentication and access
The caller needs read access to the property. The usual setup for scripts is:
- Enable the Google Analytics Data API in a Google Cloud project.
- Create a service account and download its key file.
- In GA4 Admin, under Property access management, add the service account's email address with the Viewer role.
- Point the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable at the key file.
The OAuth scope is https://www.googleapis.com/auth/analytics.readonly. A frequent first error is a 403 response that says the caller does not have permission. This usually means the service account was never added to the property, even though the Cloud project is correctly set up.
Reproducing the Pages and screens report
This request returns the ten most viewed pages over the last 28 days, with engagement figures.
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "pagePath" }],
"metrics": [
{ "name": "screenPageViews" },
{ "name": "engagedSessions" },
{ "name": "engagementRate" },
{ "name": "userEngagementDuration" }
],
"orderBys": [{ "metric": { "metricName": "screenPageViews" }, "desc": true }],
"limit": 10
}Here is how each field lines up with the report you already know:
| Interface column | API name | Notes |
|---|---|---|
| Page path and screen class | `unifiedPagePathScreen` | Covers web pages and app screens. `pagePath` is the web-only path. |
| Views | `screenPageViews` | Counts `page_view` and `screen_view` events. |
| Users | `totalUsers` or `activeUsers` | The interface's Users column corresponds to active users. |
| Event count | `eventCount` | Total number of events fired. |
| Engagement rate | `engagementRate` | A fraction between 0 and 1, not a percentage. |
| Bounce rate | `bounceRate` | Equals 1 minus engagement rate. |
| Average engagement time | Computed | `userEngagementDuration` divided by `activeUsers` (per user) or by `sessions` (per session). |
userEngagementDuration is the total engagement time in seconds across all users. The interface shows a per-user average, so you divide it yourself. If you compare the raw API number with the report column, they will not match.
What the response looks like
The response repeats your column names as headers, followed by the rows. Every value is a string, including the numbers.
{
"dimensionHeaders": [{ "name": "pagePath" }],
"metricHeaders": [
{ "name": "screenPageViews", "type": "TYPE_INTEGER" },
{ "name": "engagementRate", "type": "TYPE_FLOAT" }
],
"rows": [
{
"dimensionValues": [{ "value": "/pricing" }],
"metricValues": [{ "value": "1840" }, { "value": "0.6125" }]
}
],
"rowCount": 1
}Read metricHeaders to learn each column's type, and convert strings to numbers in your code. Values in metricValues are in the same order as the metrics in your request.
Reproducing one row of the Events report
The Events report lists event names with event count and users. To get the row for a single event, filter on eventName:
{
"dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "eventName" }],
"metrics": [{ "name": "eventCount" }, { "name": "totalUsers" }],
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"stringFilter": { "matchType": "EXACT", "value": "file_download" }
}
}
}Filters apply before aggregation, so the response contains only the matching event. Use dimensionFilter for dimension fields and metricFilter for conditions such as "event count above 100". Combine conditions with andGroup, orGroup, and notExpression.
Running a request from Python
The official client library handles authentication and the HTTP details. Install it with pip install google-analytics-data, then run this script with your property ID.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
OrderBy,
RunReportRequest,
)
PROPERTY_ID = "123456789" # replace with your numeric property ID
client = BetaAnalyticsDataClient() # reads GOOGLE_APPLICATION_CREDENTIALS
request = RunReportRequest(
property=f"properties/{PROPERTY_ID}",
date_ranges=[DateRange(start_date="28daysAgo", end_date="yesterday")],
dimensions=[Dimension(name="pagePath")],
metrics=[
Metric(name="screenPageViews"),
Metric(name="engagedSessions"),
Metric(name="engagementRate"),
Metric(name="userEngagementDuration"),
],
order_bys=[
OrderBy(
metric=OrderBy.MetricOrderBy(metric_name="screenPageViews"),
desc=True,
)
],
limit=10,
)
response = client.run_report(request)
for row in response.rows:
path = row.dimension_values[0].value
views = int(row.metric_values[0].value)
engaged = int(row.metric_values[1].value)
rate = float(row.metric_values[2].value)
seconds = float(row.metric_values[3].value)
print(f"{path}: {views} views, {engaged} engaged sessions, "
f"{rate:.1%} engagement, {seconds:.0f}s total engagement")The script converts each string explicitly and formats the rate as a percentage only at the end.
Querying a custom parameter
Earlier you registered an event parameter as a custom dimension, for example placement on a newsletter_signup event. The API name of an event-scoped custom dimension is the prefix customEvent: followed by the parameter name, so this one is customEvent:placement.
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "customEvent:placement" }],
"metrics": [{ "name": "eventCount" }],
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"stringFilter": { "matchType": "EXACT", "value": "newsletter_signup" }
}
}
}Why API numbers can differ from the interface
When an API figure disagrees with a report, check these causes first:
- Date range and time zone. Both use the property's reporting time zone.
yesterdayends at the last full day, so a report that includes today will show higher totals. - Different dimension.
pagePathandunifiedPagePathScreengroup rows differently for app data and for pages with query strings. - Data freshness. Recent data can still change for a day or more as events are processed. Do not compare today's partial figures with a finished report.
- Thresholding. When Google Signals or demographic data could identify individuals, the interface and the API can both withhold rows.
- Sampling and cardinality. Dimensions with very many unique values can be grouped into an
(other)row once a report exceeds the row limit for the property. - Report comparisons and filters. A segment or comparison applied in the interface is not part of your request unless you add an equivalent filter.
Row limits, totals, and quotas
By default a request returns up to 10,000 rows, and the maximum is 250,000 per request. For larger results, page through the data with offset and limit, and read rowCount to know when to stop.
Add "metricAggregations": ["TOTAL"] to receive a totals row. The totals for ratio metrics such as engagementRate are computed from the underlying counts. They are not an average of the row rates, which matches how the interface treats them.
Each property has a token-based quota, and heavy requests consume more of it. Set "returnPropertyQuota": true to see what remains. For scheduled jobs, request only the dimensions and metrics you need, and cache results.
Exercise
A script requests engagementRate for the pagePath /pricing and gets 0.6125. In the interface, the same page shows an engagement rate of 61.3%. A colleague also wants the average engagement time per user for that page from the API. Is the 0.6125 a bug, and which two metrics do you request to compute the average?
Show answer
It is not a bug. The API returns the rate as a fraction, and 0.6125 is 61.25%, which the interface rounds to 61.3%. For average engagement time per user, request userEngagementDuration (total seconds) and activeUsers, then divide the first by the second.