Sub topic 17
Managing audiences programmatically with the Admin API
This chapter shows how to create, read, update, and archive GA4 audiences with the Google Analytics Admin API instead of the audience builder. It assumes you can already build an audience in the UI. It also assumes you have Editor access to the property, a Google Cloud project, and basic Python and JSON skills.
When the API is worth using
The audience builder is the right tool for a handful of audiences. The Admin API is useful in these cases:
- You manage many properties, such as one per region or brand, and want the same audiences in each.
- You want audience definitions stored in version control and reviewed like code.
- You need to audit which audiences exist, how long members stay, and whether ads personalization is on.
The API cannot do everything the UI can. Treat it as a way to repeat definitions you have already tested by hand.
What the API exposes
Audiences are a child resource of a property. The path is properties/{propertyId}/audiences. Here is how the methods map to tasks.
| Method | Purpose |
|---|---|
| `create` | Define a new audience |
| `get` and `list` | Read one audience or all audiences on a property |
| `patch` | Change the mutable fields |
| `archive` | Retire an audience |
There is no hard delete. At the time of writing, the audience methods are in the v1alpha version of the API. Alpha surfaces can change, so check the current reference before you rely on a field.
The calling identity needs the https://www.googleapis.com/auth/analytics.edit scope. Reading is possible with the analytics.readonly scope. The user or service account must also have access on the property itself. A service account has to be added under Property access management, like any other user.
Anatomy of an audience resource
The JSON mirrors the builder, so each field has a UI counterpart.
displayNameanddescriptionare the labels.membershipDurationDaysis the membership duration. The maximum is 540.filterClausesis a list of clauses. Each clause is eitherINCLUDEorEXCLUDE, which matches the include and exclude sections of the builder.- Each clause holds either a
simpleFilteror asequenceFilter. - A filter has a
scope:AUDIENCE_FILTER_SCOPE_WITHIN_SAME_EVENT,AUDIENCE_FILTER_SCOPE_WITHIN_SAME_SESSION, orAUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS. filterExpressionis the condition tree. A top-levelandGroupcontainsorGroupitems. EachorGroupcontainseventFilterordimensionOrMetricFilteritems. AnotExpressionnegates one expression.eventTriggerlogs an event when a user joins the audience, as covered in the audience triggers chapter.exclusionDurationModesets whether an exclusion is temporary or permanent.adsPersonalizationEnabledis output only. You cannot set it. It reflects whether the audience can be used for personalized advertising.
Creating an audience
This script creates "Added to cart, no purchase" with a 30-day membership duration. It uses Application Default Credentials. For a service account, set GOOGLE_APPLICATION_CREDENTIALS to the key file path. Install the dependencies with pip install google-auth requests.
import json
import sys
import google.auth
from google.auth.transport.requests import AuthorizedSession
SCOPES = ["https://www.googleapis.com/auth/analytics.edit"]
BASE = "https://analyticsadmin.googleapis.com/v1alpha"
def event_clause(clause_type, event_name):
return {
"clauseType": clause_type,
"simpleFilter": {
"scope": "AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS",
"filterExpression": {
"andGroup": {
"filterExpressions": [
{
"orGroup": {
"filterExpressions": [
{"eventFilter": {"eventName": event_name}}
]
}
}
]
}
},
},
}
def main(property_id):
credentials, _ = google.auth.default(scopes=SCOPES)
session = AuthorizedSession(credentials)
body = {
"displayName": "Added to cart, no purchase",
"description": "add_to_cart in the last 30 days, excluding purchasers",
"membershipDurationDays": 30,
"filterClauses": [
event_clause("INCLUDE", "add_to_cart"),
event_clause("EXCLUDE", "purchase"),
],
}
response = session.post(f"{BASE}/properties/{property_id}/audiences", json=body)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
if __name__ == "__main__":
main(sys.argv[1])Run it as python create_audience.py 123456789, using your numeric property ID. The response includes the audience name in the form properties/123456789/audiences/987654321. Keep that name, because every later call uses it.
The add_to_cart event here is the one from the standard ecommerce setup, sent with gtag('event', 'add_to_cart', {...}). The audience can only match users whose events have already been collected.
Filtering on a parameter or user property
Conditions on plan_name or membership_tier work the same way as in the builder. The parameter or user property must first be registered as a custom dimension, as covered in the custom dimensions chapter. In the API, a parameter filter goes inside the eventFilter:
{
"eventFilter": {
"eventName": "select_plan",
"eventParameterFilterExpression": {
"andGroup": {
"filterExpressions": [
{
"orGroup": {
"filterExpressions": [
{
"dimensionOrMetricFilter": {
"fieldName": "plan_name",
"stringFilter": { "matchType": "EXACT", "value": "pro" }
}
}
]
}
}
]
}
}
}
}A user property condition uses a dimensionOrMetricFilter on its own, with the user property name as fieldName. If a filter refers to a dimension that is not registered, expect a rejected request or an audience that never fills. Check the registration first.
Reading and changing audiences
Listing is a GET on properties/{id}/audiences. A short audit script:
import sys
import google.auth
from google.auth.transport.requests import AuthorizedSession
SCOPES = ["https://www.googleapis.com/auth/analytics.readonly"]
URL = "https://analyticsadmin.googleapis.com/v1alpha/properties/{}/audiences"
credentials, _ = google.auth.default(scopes=SCOPES)
session = AuthorizedSession(credentials)
token = None
while True:
params = {"pageToken": token} if token else {}
data = session.get(URL.format(sys.argv[1]), params=params).json()
for a in data.get("audiences", []):
print(a["displayName"], a.get("membershipDurationDays"), a.get("adsPersonalizationEnabled"))
token = data.get("nextPageToken")
if not token:
breakList results are paginated, so follow nextPageToken. Otherwise you will miss audiences on properties with many of them.
Most of the definition is immutable after creation. These fields cannot be changed, so confirm against the current reference:
filterClausesmembershipDurationDaysexclusionDurationMode
To change any of them, create a new audience with the new definition. Then call archive on the old one once the replacement is in use. A patch request needs an updateMask query parameter naming the fields to change, such as updateMask=displayName,description.
Gotchas and limits
- No backfill. An audience created by the API starts collecting members from the moment it is created, as in the UI. A new audience will look small for days.
- Linking is separate. Creating an audience does not link Google Ads. The link and the ads personalization settings must already exist, as covered in the Google Ads linking and consent chapters.
- Property limits apply. A standard property allows 100 audiences, and the API enforces this just as the UI does. Scripts that create audiences in a loop should count first.
- Naming matters at scale. Use a consistent prefix, such as
rmk_for remarketing andana_for analysis, so that list output is easy to filter. - Quotas. Admin API requests are rate limited per project and per property. Add retry with backoff on
429responses.
Exercise
You created an audience through the API with membershipDurationDays set to 30. A week later the marketing team wants 90 days. Can you patch the audience, and what should you do instead?
Show answer
No. membershipDurationDays is immutable, and patch only changes fields such as displayName and description. Create a new audience with the same filterClauses and membershipDurationDays set to 90. Once campaigns use the new audience, archive the old one. The new audience starts empty, so plan for it to fill gradually.