Sub topic 14
Querying recent activity with the Realtime Reporting API
The Realtime report in the GA4 interface has a programmatic counterpart: the runRealtimeReport method of the Google Analytics Data API. It returns the same kind of recent-activity data as the Realtime cards, so a script can check tracking, feed a monitoring dashboard, or run a smoke test after a deployment.
This chapter assumes you have read the earlier chapters on the Realtime report, its time window, and the difference between Realtime and DebugView. It also assumes you can send an HTTP request with curl or run a short Python script, and that you have at least Viewer access to the property.
What the API gives you
runRealtimeReport queries the same recent window as the Realtime report. That window is the last 30 minutes for standard properties and the last 60 minutes for Analytics 360 properties. The data is event-level and aggregated, so you can count events, users and views, but you cannot inspect one device's event stream. DebugView remains the tool for that.
The method is separate from runReport, which serves standard reports. The two differ in several ways:
| Aspect | `runRealtimeReport` | `runReport` |
|---|---|---|
| Time scope | Last 30 minutes (60 for 360) | Any date range |
| Time filter | `minuteRanges` | `dateRanges` |
| Dimensions and metrics | A small, fixed subset | The full API schema |
| Freshness | Seconds to a minute or so | Hours, because of processing |
| Typical use | Verification, live monitoring | Analysis and reporting |
How a request flows
The working model is simple. Your code authenticates, names a property, and sends dimensions, metrics and optional filters. The API answers with headers that describe the columns and rows that hold the values.
Before you send a request
Three details cause most first-time failures.
- Use the property ID, not the measurement ID. The property ID is a number such as
123456789, found under Admin, Property settings. The measurement ID (G-XXXXXXXXXX) identifies a data stream and is not valid in the URL. - Use the right scope. The access token needs
https://www.googleapis.com/auth/analytics.readonly. A token for another Google API returns a permission error. - Grant the identity access to the property. If you authenticate with a service account, add its email address to the property's access management with the Viewer role. Enabling the Google Analytics Data API in the Cloud project is also required.
Your first request
This request returns the count of each event name in the recent window, the same data as the Realtime event count card.
curl -X POST "https://analyticsdata.googleapis.com/v1beta/properties/PROPERTY_ID:runRealtimeReport" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"dimensions": [{ "name": "eventName" }],
"metrics": [{ "name": "eventCount" }]
}'The response contains dimensionHeaders, metricHeaders and rows. Each row holds dimensionValues and metricValues in the same order as the headers. All values arrive as strings, even numbers, so convert them in your code. A rowCount field gives the total number of rows available.
If no events arrived in the window, the response has no rows field at all. Your code must treat a missing rows as zero results, not as an error.
Dimensions and metrics you can use
Realtime accepts only a subset of the API schema. Using a field from the standard schema returns an error.
- Dimensions include
eventName,minutesAgo,country,city,deviceCategory,platform,streamId,streamName,appVersion,unifiedScreenNameand audience fields. - Metrics are
activeUsers,eventCount,keyEventsandscreenPageViews. - Custom user-scoped dimensions can be used in the form
customUser:parameter_name.
Event-scoped custom dimensions, session metrics, traffic source fields and page path are not available here. If you need to see a custom event parameter, DebugView is the right tool.
The minutesAgo dimension is useful for a quick timeline. A value of 00 means the current minute, 01 the minute before, and so on. Pair it with eventCount to see whether events are still flowing or stopped a few minutes ago.
Narrowing the time window
By default a request covers the whole window. The minuteRanges field restricts it. Each range has an optional name, a startMinutesAgo and an endMinutesAgo. The start value is the older boundary, so it is the larger number.
{
"dimensions": [{ "name": "eventName" }],
"metrics": [{ "name": "eventCount" }],
"minuteRanges": [
{ "name": "last5", "startMinutesAgo": 4, "endMinutesAgo": 0 },
{ "name": "previous5", "startMinutesAgo": 9, "endMinutesAgo": 5 }
]
}You can send up to two ranges. The range 0 to 0 is only the current minute. Allowed values run from 0 to 29 for standard properties and 0 to 59 for 360 properties. When you use minuteRanges, the API adds a dateRange dimension to the response, so each row says which range it belongs to. Always read the column positions from the headers, not from fixed indexes.
Filtering to one event
To check one event after a code change, filter the report to that event name.
curl -X POST "https://analyticsdata.googleapis.com/v1beta/properties/PROPERTY_ID:runRealtimeReport" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"dimensions": [{ "name": "eventName" }, { "name": "streamName" }],
"metrics": [{ "name": "eventCount" }],
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"stringFilter": { "matchType": "EXACT", "value": "sign_up" }
}
},
"limit": 10
}'Other useful fields are metricFilter (for example, only rows above a count), orderBys, metricAggregations (adds totals) and returnPropertyQuota (reports how much quota you have left). Combine conditions with andGroup, orGroup or notExpression inside dimensionFilter.
Calling the API from Python
For repeatable checks, a client library handles authentication and parsing. Install google-analytics-data and set GOOGLE_APPLICATION_CREDENTIALS to the path of your service account key file.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
Dimension,
Metric,
MinuteRange,
RunRealtimeReportRequest,
)
PROPERTY_ID = "123456789" # numeric property ID, not G-XXXXXXXXXX
def recent_event_counts(minutes: int = 5) -> dict:
client = BetaAnalyticsDataClient()
request = RunRealtimeReportRequest(
property=f"properties/{PROPERTY_ID}",
dimensions=[Dimension(name="eventName")],
metrics=[Metric(name="eventCount")],
minute_ranges=[
MinuteRange(name="recent", start_minutes_ago=minutes - 1, end_minutes_ago=0)
],
)
response = client.run_realtime_report(request)
dim_names = [h.name for h in response.dimension_headers]
counts = {}
for row in response.rows:
values = dict(zip(dim_names, (v.value for v in row.dimension_values)))
counts[values["eventName"]] = counts.get(values["eventName"], 0) + int(
row.metric_values[0].value
)
return counts
if __name__ == "__main__":
counts = recent_event_counts()
if counts.get("purchase", 0) == 0:
print("No purchase events in the last 5 minutes")
else:
print(counts)The function reads column names from the headers and sums rows by event name, so it keeps working if the API adds the dateRange column. A missing rows field simply produces an empty dictionary.
Quotas and polling
Realtime requests draw on the property's quota, so a loop that polls every second wastes it. Quota is counted per property in tokens, with limits per day, per hour and for concurrent requests. A request with many dimensions, a long window or a high row count costs more. Set returnPropertyQuota to true while you develop so you can see consumption.
For verification, poll no more often than every 30 to 60 seconds. Realtime data is aggregated, so faster polling shows nothing new.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 403 `PERMISSION_DENIED` | Identity has no access to the property, or the API is not enabled | Add the account as Viewer and enable the Data API in the Cloud project |
| 400 "Field ... is not a valid dimension" | A field from the standard schema was used | Use only the Realtime dimensions and metrics |
| 404 or "property not found" | Measurement ID used in the URL | Use the numeric property ID |
| 401 `UNAUTHENTICATED` | Expired token or wrong scope | Request a new token with the `analytics.readonly` scope |
| Response has no `rows` | No matching events in the window | Treat as zero, then check the tracking |
| 429 quota error | Polling too fast or requests too heavy | Slow down and reduce dimensions |
When to choose the API
Use the interface when you are debugging by hand. Use the API when the check must run unattended, for example:
- A post-deployment test that fails the pipeline if
purchasehas zero events after a scripted checkout. - A monitor that alerts when
eventCountfor a key event drops to zero during business hours. - A script that compares event counts across two
minuteRangesto spot a sudden change after a release.
Exercise
Your script calls runRealtimeReport with minuteRanges of startMinutesAgo 4 and endMinutesAgo 0, and eventName and eventCount as the dimension and metric. The response has three columns per row, not two. Which column was added, why, and how should the code avoid depending on column positions?
Show answer
The API adds a dateRange dimension whenever minuteRanges is used, so each row says which range it belongs to. The code should read dimensionHeaders and metricHeaders to find the position of each field by name (for example, building a dictionary from header names and values) instead of using fixed indexes.
Exercise
A deployment test queries the Realtime API one minute after a scripted sign-up and gets a 200 response with no rows field. Is this an API error? What should the test do next?
Show answer
It is not an error. A missing rows field means no events matched in the window. The test should treat the count as zero, wait and retry for a short period in case of delay, and if it is still empty, check the tracking (stream, event name, debug mode) with DebugView.