Sub topic 16
Reproducing an exploration with the GA4 Data API
A Free-form exploration is a saved query plus a layout. The query part (date range, dimensions, metrics, filters) maps almost one-to-one onto a request to the GA4 Data API. This chapter shows that mapping, so you can move a table you built in Explore into a script, a spreadsheet connector, or a dashboard.
This chapter assumes you have read the earlier chapters on dimensions, metrics, scopes, Tab Settings and filters. It also assumes you can read JSON and have access to a GA4 property with at least Viewer permissions.
Why the API is a useful companion
Explorations are good for discovery. They are less good when you need the same numbers every morning, in a place other than the GA4 interface. The Data API fills that gap. Its core method, runReport, takes a request body and returns rows of dimension values and metric values.
Both the exploration and the API read from the same event-based data model. The two will not always match exactly, for reasons covered in the last section of this chapter.
Mapping Explore settings to request fields
Every choice you make in the Variables and Tab Settings panels has a counterpart in the request body.
| Explore setting | Data API field |
|---|---|
| Date range in Tab Settings | `dateRanges` (`startDate`, `endDate`) |
| Dimensions imported in Variables, placed in Rows or Columns | `dimensions` |
| Metrics imported in Variables, placed in Values | `metrics` |
| Filter in Tab Settings | `dimensionFilter` or `metricFilter` |
| Number of rows shown | `limit` and `offset` |
| Sort by a value column | `orderBys` |
| Segment applied to the tab | A filter on the equivalent dimension, or a different approach (see below) |
The layout choices do not appear in the request. Whether a dimension sits in Rows or Columns, whether a cell is plain text or a heat map, and which visualization you chose are all presentation. The API returns a flat list of rows. If you want a pivot, you build it yourself from that list. The API also has a pivots field for this, but most scripts reshape the result in code.
A request that matches a channel-by-device table
Suppose your exploration has these settings:
- Rows: Session default channel group and Device category.
- Values: Sessions, Engaged sessions and Total users.
- Date range: the last 28 days.
The matching request body is:
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "yesterday" }],
"dimensions": [
{ "name": "sessionDefaultChannelGroup" },
{ "name": "deviceCategory" }
],
"metrics": [
{ "name": "sessions" },
{ "name": "engagedSessions" },
{ "name": "totalUsers" }
],
"limit": 25
}Notice that the UI names and the API names differ. The interface says "Session default channel group". The API says sessionDefaultChannelGroup. The API names are camelCase and listed in the Data API schema documentation. You can also call the getMetadata method, which returns every dimension and metric available to your property, including custom ones.
The date strings 28daysAgo and yesterday are relative. They behave like the "Last 28 days" preset in Explore, which also ends yesterday by default. Using relative dates keeps a scheduled script current. Use YYYY-MM-DD strings when you need a fixed period.
Rows, columns and the flat response
Each row in the response holds the dimension values first, in the order you listed them, then the metric values in the order you listed them. A response row for the request above looks like this in outline:
{
"dimensionValues": [{ "value": "Organic Search" }, { "value": "mobile" }],
"metricValues": [{ "value": "4210" }, { "value": "2987" }, { "value": "3650" }]
}All values arrive as strings. Convert metric values to numbers before you calculate with them.
Translating a filter
In Explore, a filter lives in Tab Settings. You choose a dimension, a match type such as "exactly matches" or "contains", and a value. The API expresses the same idea with dimensionFilter.
This request keeps only mobile traffic:
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "sessionDefaultChannelGroup" }],
"metrics": [{ "name": "sessions" }],
"dimensionFilter": {
"filter": {
"fieldName": "deviceCategory",
"stringFilter": { "matchType": "EXACT", "value": "mobile" }
}
}
}A few details are worth knowing:
- The filtered field does not have to appear in
dimensions. Here the table has only the channel group, yet the filter still usesdeviceCategory. matchTypeaccepts values such asEXACT,CONTAINS,BEGINS_WITH,ENDS_WITHandFULL_REGEXP. These correspond to the match options in the Explore filter menu.- To combine conditions, wrap them in
andGroup,orGroupornotExpression. - A filter on a metric, such as "sessions greater than 100", goes in
metricFilter. It applies after aggregation, like a filter on a value column.
Device category values are lowercase (mobile, desktop, tablet). A string match is case-sensitive unless you set caseSensitive to false, so a typo in case returns an empty result and no error.
Segments are not a direct field
A segment in Explore can be user-based, session-based or event-based, with sequences and exclusions. The Data API runReport method has no segment parameter that mirrors this.
You have three practical options:
- Replace the segment with a
dimensionFilterwhen the segment is a simple condition, such as "Device category = mobile". - Add the segment's defining dimension to
dimensionsand compare the groups in your own code, which mimics a segment comparison. - Use an audience or a custom dimension that records the grouping, then filter or break down by it.
Segments with sequences, such as "viewed a product, then purchased", have no simple filter equivalent. Rebuild those with event-level filters, or keep them in Explore.
Compatibility rules still apply
The scope and compatibility rules you met earlier are enforced by the API too. If you request an incompatible combination, such as an item-scoped dimension with a session-scoped metric that does not support it, the API returns an error instead of a greyed-out field. Use the checkCompatibility method to test a set of dimensions and metrics before you run a report. It tells you which fields are compatible with your current selection.
Why the numbers may not match exactly
Even with equivalent settings, the two outputs can differ. Check these causes first:
- Thresholds. Both can withhold rows to protect user privacy, depending on your property's reporting identity and Google signals settings.
- Sampling. Explorations can be sampled on large date ranges. API requests to standard properties can also return sampled or approximated data, and the response metadata tells you when that happened.
- Time zone and freshness. Both use the property's reporting time zone, but a request run at a different time sees different recent data. Recent days can still change as events are processed.
- Row limits.
limitdefaults to 10,000 rows and has a maximum, and Explore shows its own number of rows per tab. Compare the same number of rows. - Totals. Unique-count metrics such as
totalUsersare not additive. A grand total is not the sum of its rows. Request totals withmetricAggregationsinstead of adding rows yourself. - Quotas. The Data API enforces token-based quotas per property. Large, complex requests use more tokens, and the response can report your remaining quota if you ask for
returnPropertyQuota.
A short checklist for porting a tab
- Write down the tab's date range, dimensions, metrics and filters.
- Look up the API name of each field, or call
getMetadata. - Build the request body and test it for compatibility.
- Run it, and compare the top rows with the exploration.
- If the numbers differ, check thresholds, sampling, time zone and row limits in that order.
Exercise
Your exploration shows Sessions by Landing page, filtered to Device category "exactly matches" desktop. Write the dimensions, metrics and dimensionFilter parts of the matching Data API request. Then explain why a script that sums the rows of a Total users column may disagree with the exploration's total.
Show answer
The request needs "dimensions": [{ "name": "landingPage" }], "metrics": [{ "name": "sessions" }], and "dimensionFilter": { "filter": { "fieldName": "deviceCategory", "stringFilter": { "matchType": "EXACT", "value": "desktop" } } }. The sums can disagree because Total users counts unique users. One user who visited several landing pages appears in several rows, so adding the rows counts that person more than once. The exploration's total is deduplicated. In the API, request metricAggregations: ["TOTAL"] to get the same figure.
Exercise
A colleague's Explore tab uses a segment of users who viewed a product page and later purchased. Can you reproduce it with a single dimensionFilter in runReport? Give your answer and one alternative.
Show answer
No. That segment is a sequence, and a dimensionFilter evaluates conditions on rows, not ordered steps over time. One alternative is to keep the analysis in Explore, where sequence segments are supported. Another is to approximate it with event-level reports, for example by requesting eventName counts for view_item and purchase and comparing them, accepting that this does not enforce the order or the same-user condition.