Sub topic 16
Running a funnel report with the Data API
This chapter assumes you can already build a funnel in the Explore workspace. It also assumes you know the difference between open and closed funnels, and that you know how steps, breakdowns and time limits behave. Here you will reproduce that work in code with the Data API's runFunnelReport method.
Why query a funnel programmatically
The Explore interface suits one-off analysis. An API call suits repeated work, such as:
- a weekly checkout report sent to a team chat
- a funnel table loaded into a warehouse
- a dashboard outside GA4
- the same funnel run across many properties
The method belongs to the alpha channel (v1alpha) of the Data API. Alpha means field names, behavior and availability can change with little notice. Check the current reference before you build anything critical on it.
How the request maps to the Explore settings
A runFunnelReport request is a JSON body sent to a property-level endpoint. Most Explore settings have a matching field.
| Explore setting | Request field |
|---|---|
| Date range | `dateRanges` |
| Open or closed funnel | `funnel.isOpenFunnel` |
| Step name and condition | `funnel.steps[].name`, `filterExpression` |
| Directly or indirectly followed by | `steps[].isDirectlyFollowedBy` |
| Time limit between steps | `steps[].withinDurationFromPriorStep` |
| Breakdown | `funnelBreakdown` |
| Next action | `funnelNextAction` |
| Standard or trended view | `funnelVisualizationType` |
| Segment comparison | `segments` |
The endpoint has this form, where {propertyId} is the numeric property ID, not the measurement ID that starts with G-:
POST https://analyticsdata.googleapis.com/v1alpha/properties/{propertyId}:runFunnelReportThe caller needs the https://www.googleapis.com/auth/analytics.readonly scope. The authenticated user or service account also needs access to the property.
A closed three-step funnel
This body matches the purchase funnel you built in the interface. The three steps are view_item, add_to_cart and purchase.
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "yesterday" }],
"funnel": {
"isOpenFunnel": false,
"steps": [
{
"name": "View item",
"filterExpression": { "funnelEventFilter": { "eventName": "view_item" } }
},
{
"name": "Add to cart",
"filterExpression": { "funnelEventFilter": { "eventName": "add_to_cart" } }
},
{
"name": "Purchase",
"filterExpression": { "funnelEventFilter": { "eventName": "purchase" } }
}
]
}
}With isOpenFunnel set to false, a user counts only if they enter at step 1. Setting it to true lets users enter at any step. The behavior matches the Explore setting, so the numbers should agree with the interface when the date range and settings are the same.
Sending the request from Python
This script uses Google's default credentials and the google-auth and requests libraries. It posts the body above and prints each step with its user count and rates.
import google.auth
from google.auth.transport.requests import AuthorizedSession
PROPERTY_ID = "123456789" # replace with your numeric property ID
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
session = AuthorizedSession(credentials)
url = f"https://analyticsdata.googleapis.com/v1alpha/properties/{PROPERTY_ID}:runFunnelReport"
def step(name, event):
return {
"name": name,
"filterExpression": {"funnelEventFilter": {"eventName": event}},
}
body = {
"dateRanges": [{"startDate": "28daysAgo", "endDate": "yesterday"}],
"funnel": {
"isOpenFunnel": False,
"steps": [
step("View item", "view_item"),
step("Add to cart", "add_to_cart"),
step("Purchase", "purchase"),
],
},
}
response = session.post(url, json=body)
response.raise_for_status()
table = response.json()["funnelTable"]
dim_names = [h["name"] for h in table.get("dimensionHeaders", [])]
metric_names = [h["name"] for h in table.get("metricHeaders", [])]
for row in table.get("rows", []):
dims = dict(zip(dim_names, (v["value"] for v in row["dimensionValues"])))
mets = dict(zip(metric_names, (v["value"] for v in row["metricValues"])))
print(dims, mets)The script builds each row from the header names rather than from fixed positions. When you add a breakdown, the dimension columns change. Reading by name keeps the code working.
Reading the response
The response has these parts:
funnelTableholds one row per step, or per step and breakdown value. Its metrics includeactiveUsers,funnelStepCompletionRate,funnelStepAbandonmentsandfunnelStepAbandonmentRate.funnelVisualizationholds the data behind the chart, which is useful when you request a trended funnel.propertyQuotaappears when you setreturnPropertyQuotatotrue.
The completion rate for a step is the share of users who reached that step among those who reached the one before it. It is not measured against step 1. If you want overall conversion, divide the last step's users by the first step's users yourself.
Time limits, directness and conditions
Step-level fields give you the same controls as the Explore step editor. This step requires that add_to_cart follow view_item immediately and within 30 minutes:
{
"name": "Add to cart",
"isDirectlyFollowedBy": true,
"withinDurationFromPriorStep": "1800s",
"filterExpression": {
"funnelEventFilter": { "eventName": "add_to_cart" }
}
}The duration is a string in seconds with an s suffix. If you leave out isDirectlyFollowedBy, the step is indirectly followed by the previous one, so other events may occur in between.
To add a parameter condition, nest a funnelParameterFilterExpression inside the event filter:
{
"funnelEventFilter": {
"eventName": "purchase",
"funnelParameterFilterExpression": {
"funnelParameterFilter": {
"eventParameterName": "currency",
"stringFilter": { "matchType": "EXACT", "value": "USD" }
}
}
}
}You can combine conditions with andGroup, orGroup and notExpression.
Breakdowns, next action and trended view
Add funnelBreakdown to split every step by a dimension:
{
"funnelBreakdown": {
"breakdownDimension": { "name": "deviceCategory" },
"limit": 5
}
}The limit caps how many breakdown values return. Values past the cap are grouped into an "(other)" row. Set funnelVisualizationType to TRENDED_FUNNEL to get conversion over time, or leave it as the default STANDARD_FUNNEL. Use funnelNextAction to ask what users do after a step.
Limits and common errors
- Different numbers from the interface. Check that
isOpenFunnel, the date range, the step conditions and any segments match. Differences in timezone or data freshness can also matter. - Thresholding. Data API reports can withhold or aggregate rows to protect user privacy, just as the interface does. Small breakdown values are the most likely to vanish.
- Quota errors. Funnel requests use property quota. Set
returnPropertyQuotatotrueto see how much you have left, and spread out scheduled jobs. - A 403 response. The credentials lack the scope, or the account has no access to that property.
- Zero users at a step. The event name may be misspelled, or the event may not be instrumented. Event names are case-sensitive.
Exercise
Exercise
You run a closed funnel through the API and get fewer users at step 1 than the same funnel shows in Explore. You have set isOpenFunnel to false in both. Name two request or report differences you would check, and say which field controls each.
Show answer
Check the date range (dateRanges) and the segments (segments) or filters applied in one place but not the other. A segment in Explore that is missing from the request, or the reverse, changes who qualifies at step 1. Step conditions such as funnelParameterFilterExpression and thresholding on small counts are other possible causes.