Sub topic 14
Querying custom definitions with the Data API and BigQuery
This chapter assumes you have already registered at least one custom dimension or custom metric in Admin and sent matching data. You should also be comfortable reading JSON and basic SQL. Here you will pull your custom definitions out of GA4 programmatically through two routes. The Google Analytics Data API returns processed report data, and the BigQuery export gives you raw event rows.
Two routes, two different rules
The Data API and BigQuery both expose your custom data, but they treat registration very differently.
| Aspect | Data API | BigQuery export |
|---|---|---|
| Needs registration in Admin | Yes. Unregistered parameters cannot be requested. | No. Every sent parameter is in the export. |
| Shape of data | Aggregated rows, like a report | One row per event, with nested fields |
| Name you use | `customEvent:plan_tier` | `key = 'plan_tier'` inside `event_params` |
| Applies GA4 processing | Yes (thresholds, cardinality limits, quotas) | No, raw data |
| Data before registration | Not available | Available, because it was always exported |
The last row matters most. Registration is not retroactive in reports, but BigQuery holds the raw parameter values from the day you linked the export. If you sent plan_tier for three months before registering it, you can still recover those months from BigQuery.
Data API: naming custom definitions
In a Data API request, each custom definition has an API name built from its scope prefix and its parameter or property name.
| Scope | Prefix | Example |
|---|---|---|
| Event | `customEvent:` | `customEvent:plan_tier` |
| User | `customUser:` | `customUser:customer_type` |
| Item | `customItem:` | `customItem:item_color` |
Custom metrics are event-scoped, so they use customEvent: as well, for example customEvent:video_length_seconds. You use the same name field in dimensions or metrics depending on what you registered. The name is the event parameter name, not the display name you typed in Admin. If you registered plan_tier with the display name "Plan tier", the API still wants customEvent:plan_tier.
A basic request
This request body counts events by plan_tier over the last 28 days. You send it to properties/PROPERTY_ID:runReport.
{
"dateRanges": [{ "startDate": "28daysAgo", "endDate": "today" }],
"dimensions": [{ "name": "customEvent:plan_tier" }],
"metrics": [{ "name": "eventCount" }]
}The same request in Python
The official client library (pip install google-analytics-data) wraps the same call. It reads credentials from Application Default Credentials. The account you authenticate with needs at least Viewer access on the property.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
PROPERTY_ID = "123456789" # replace with your numeric property ID
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=f"properties/{PROPERTY_ID}",
date_ranges=[DateRange(start_date="28daysAgo", end_date="today")],
dimensions=[Dimension(name="customEvent:plan_tier")],
metrics=[Metric(name="eventCount")],
)
response = client.run_report(request)
for row in response.rows:
plan_tier = row.dimension_values[0].value
count = row.metric_values[0].value
print(plan_tier, count)Every value comes back as a string, including numbers. Convert them in your own code.
Using a custom metric
A registered custom metric goes in the metrics list. This body shows total video length per plan tier. The metric's aggregation is always a sum of the registered parameter, so the result is a total, not an average.
{
"dateRanges": [{ "startDate": "7daysAgo", "endDate": "today" }],
"dimensions": [{ "name": "customEvent:plan_tier" }],
"metrics": [
{ "name": "eventCount" },
{ "name": "customEvent:video_length_seconds" }
]
}To get an average, divide in your own code, or use a calculated metric in the GA4 interface.
Discovering what is registered
You do not have to guess names. The getMetadata method (GET properties/PROPERTY_ID/metadata) lists every dimension and metric available to that property, including custom ones. Custom entries have customDefinition: true, which makes them easy to filter. A name missing from this list is the first thing to check when a request fails with an "unknown dimension" error.
The checkCompatibility method tells you whether a set of dimensions and metrics can be combined. It helps when a mix of scopes is rejected. Item-scoped dimensions, for example, pair only with item metrics such as itemRevenue and itemsViewed, not with arbitrary event metrics.
Data API limits that affect custom definitions
- Quotas. Each property has hourly and daily token budgets, and a cap on concurrent requests. Complex requests with many dimensions or long date ranges cost more tokens. Set
returnPropertyQuotatotruein the request to see how much you have left. - Cardinality. A custom dimension with very many distinct values can collapse into an
(other)row. Reports with high-cardinality dimensions behave the same way in the interface. The fix is at design time, as covered in the cardinality chapter. - Thresholds. Where Google Signals or similar features are active, small user counts can be withheld to protect privacy, so rows may be missing.
- Freshness. Newly sent data can take several hours to appear in the API, and a freshly registered definition takes up to about a day to start populating.
BigQuery: reading raw parameters
When you link a property to BigQuery, GA4 writes a table per day named events_YYYYMMDD in a dataset called analytics_PROPERTY_ID. Today's partial data lands in events_intraday_YYYYMMDD when streaming export is enabled. Standard properties have a daily export cap of one million events, so check your volume before depending on this route.
Each row is one event. Parameters are not separate columns. They live in a repeated record called event_params, where each element has a key and a value struct with four typed fields: string_value, int_value, float_value and double_value. User properties sit in a similar user_properties record, which also holds set_timestamp_micros.
Extracting an event parameter
You pull a parameter out with a correlated subquery over UNNEST:
SELECT
(SELECT value.string_value
FROM UNNEST(event_params)
WHERE key = 'plan_tier') AS plan_tier,
COUNT(*) AS events
FROM `my-project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261128'
AND event_name = 'select_plan'
GROUP BY plan_tier
ORDER BY events DESC;The _TABLE_SUFFIX filter limits which daily tables are scanned. This controls cost, because BigQuery bills by bytes read.
Extracting a numeric value
A number may be stored as int_value or double_value, depending on how it was sent. 184 arrives as an integer and 29.99 as a double. Use COALESCE to read either without having to know which:
SELECT
(SELECT value.string_value
FROM UNNEST(event_params)
WHERE key = 'plan_tier') AS plan_tier,
SUM(
(SELECT COALESCE(value.int_value, value.double_value)
FROM UNNEST(event_params)
WHERE key = 'video_length_seconds')
) AS total_video_seconds
FROM `my-project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261128'
AND event_name = 'video_complete'
GROUP BY plan_tier;Extracting a user property
The pattern is identical, with user_properties in place of event_params:
SELECT
(SELECT value.string_value
FROM UNNEST(user_properties)
WHERE key = 'customer_type') AS customer_type,
COUNT(DISTINCT user_pseudo_id) AS users
FROM `my-project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261128'
GROUP BY customer_type;Item parameters appear inside the repeated items record. Inspect the schema of your own export in the BigQuery console to see exactly which item fields it contains. Then use UNNEST(items) to read them.
Common errors in BigQuery
- Wrong value field. Selecting
value.string_valuefor a numeric parameter returnsNULLfor every row. Check the schema or run a quickSELECTof all four value fields. - Case and spelling. Keys are case-sensitive.
Plan_Tierandplan_tierare different keys, and both would be exported if both were sent. - Comparing with the interface. BigQuery counts will not match GA4 reports exactly. Reports apply processing, estimated user counts and modeling that raw rows do not.
- Forgetting the date filter. A wildcard query without
_TABLE_SUFFIXscans every day and costs more.
Choosing a route
Use the Data API when you need numbers that agree with the GA4 interface, for example in a dashboard that stakeholders will compare against reports. Use BigQuery when you need history from before registration, row-level joins with other data, or parameters that you never registered because you were near a property limit. Many teams use both. They register the 10 to 20 definitions that analysts use daily, and they leave the rest in the raw export.
Exercise
You sent a store_region parameter on an offline_sale event for two months but never registered it. A colleague asks for sales by region for the full two months. Which route can answer this, and what are the key details of the query?
Show answer
BigQuery. The export keeps every sent parameter, whether or not it is registered, so the full two months exist in the events_* tables. The query filters event_name = 'offline_sale', reads store_region with (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'store_region'), and limits the date range with _TABLE_SUFFIX. The Data API cannot help for the earlier period. Registering store_region now would only populate customEvent:store_region from the registration date onward.
Exercise
A Data API call using customEvent:Plan Tier fails, but the dimension appears in Admin as "Plan Tier". What is wrong, and how do you find the correct name?
Show answer
"Plan Tier" is the display name. The API name is customEvent: plus the event parameter name, here customEvent:plan_tier. Call getMetadata for the property and look for entries with customDefinition: true to see the exact API names.