Sub topic 13
Reading and Updating Retention with the Admin API
This chapter shows how to read and change a property's event data retention settings through the Google Analytics Admin API. It assumes you have read the earlier chapters on retention periods and "reset user data on new activity". It also assumes you can use curl or Python, and that you know what an OAuth access token is. The goal is to make the retention settings repeatable and checkable across many properties, without clicking through the Admin interface.
Why use the API for retention
The Admin interface is fine for one property. It becomes error-prone when you manage dozens of properties, or when a policy says "every property must keep 14 months of event data". The API gives you three things:
- A way to read the current value without opening each property.
- A way to set the value the same way every time, which you can keep in version control.
- A way to check settings on a schedule and report drift.
The resource model
Each property has exactly one dataRetentionSettings resource. You cannot create or delete it. You can only read it (GET) and update it (PATCH). Its name follows this pattern:
properties/{propertyId}/dataRetentionSettings{propertyId} is the numeric property ID, not the measurement ID (G-XXXXXXX) and not the account ID. You find the property ID in Admin > Property details.
The resource has two settings you can change:
| Field | Type | Meaning |
|---|---|---|
| `eventDataRetention` | enum | How long user-level event data is kept before it is deleted. |
| `resetUserDataOnNewActivity` | boolean | If true, the retention clock for a user restarts each time that user returns. |
The enum values are TWO_MONTHS, FOURTEEN_MONTHS, TWENTY_SIX_MONTHS, THIRTY_EIGHT_MONTHS and FIFTY_MONTHS. A value of RETENTION_DURATION_UNSPECIFIED is a placeholder and you should never send it. Standard properties accept only TWO_MONTHS and FOURTEEN_MONTHS. The longer values are for Analytics 360 properties.
The API version matters. The examples here use v1beta, which is the stable surface that includes this resource.
Permissions and authentication
Reading and writing need different OAuth scopes:
| Operation | Scope | Property role needed |
|---|---|---|
| Read settings | `https://www.googleapis.com/auth/analytics.readonly` | Viewer or higher |
| Update settings | `https://www.googleapis.com/auth/analytics.edit` | Editor or higher |
The identity that calls the API must have access to the property. For automation, a common setup is a service account. You add the service account's email address as a user on the property (or on the account) with the role you need. Enabling the Google Analytics Admin API in the Google Cloud project is also required. Without that step, calls fail with a 403 error even when the user roles are correct.
Reading the current settings
A read is a plain GET. This request uses the access token in an environment variable:
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://analyticsadmin.googleapis.com/v1beta/properties/123456789/dataRetentionSettings"A typical response looks like this:
{
"name": "properties/123456789/dataRetentionSettings",
"eventDataRetention": "TWO_MONTHS",
"resetUserDataOnNewActivity": true
}Two months is the default for new properties, which is why a quick read often reveals properties that were never changed. Many teams find out at this point that Explorations stop working on date ranges older than two months, which the earlier chapter on retention impact explains.
Updating with PATCH and updateMask
An update is a PATCH request with two parts: a JSON body that holds the new values, and an updateMask query parameter that names which fields to change.
curl -s -X PATCH \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"eventDataRetention":"FOURTEEN_MONTHS","resetUserDataOnNewActivity":true}' \
"https://analyticsadmin.googleapis.com/v1beta/properties/123456789/dataRetentionSettings?updateMask=eventDataRetention,resetUserDataOnNewActivity"The mask is a comma-separated list of field names, with no spaces. The API changes only the fields in the mask and ignores the rest of the body. This has practical consequences:
- If a field is in the body but not in the mask, nothing changes for that field, and you get no error. This is a common silent failure.
- If a field is in the mask but missing from the body, the API resets that field to its default value. For the boolean, that means
false. - If you leave the mask out, the request is rejected with a 400 error, because the mask is required.
To change only the reset option and leave the period alone, send a mask that names only resetUserDataOnNewActivity.
The same calls in Python
For scripts, the official client library is easier than raw HTTP because it handles authentication and the field mask type. Install it with pip install google-analytics-admin. This example uses Application Default Credentials, so the credentials need the analytics.edit scope.
from google.analytics.admin_v1beta import AnalyticsAdminServiceClient
from google.analytics.admin_v1beta.types import DataRetentionSettings
from google.protobuf.field_mask_pb2 import FieldMask
PROPERTY_ID = "123456789"
NAME = f"properties/{PROPERTY_ID}/dataRetentionSettings"
client = AnalyticsAdminServiceClient()
current = client.get_data_retention_settings(name=NAME)
print("Before:", current.event_data_retention.name,
current.reset_user_data_on_new_activity)
desired = DataRetentionSettings(
name=NAME,
event_data_retention=DataRetentionSettings.RetentionDuration.FOURTEEN_MONTHS,
reset_user_data_on_new_activity=True,
)
updated = client.update_data_retention_settings(
data_retention_settings=desired,
update_mask=FieldMask(
paths=["event_data_retention", "reset_user_data_on_new_activity"]
),
)
print("After:", updated.event_data_retention.name,
updated.reset_user_data_on_new_activity)The client library uses snakecase names (`eventdata_retention) in the mask, while the REST API uses camelCase (eventDataRetention`). Mixing the two styles is a frequent cause of "field not found" errors.
Auditing many properties
The retention endpoint is per property, so an audit needs a list of properties first. accountSummaries returns every account and property the caller can see in a single listing. This script flags any property that does not meet a policy of 14 months with reset enabled:
from google.analytics.admin_v1beta import AnalyticsAdminServiceClient
from google.analytics.admin_v1beta.types import DataRetentionSettings
REQUIRED = DataRetentionSettings.RetentionDuration.FOURTEEN_MONTHS
client = AnalyticsAdminServiceClient()
for account in client.list_account_summaries():
for prop in account.property_summaries:
name = f"{prop.property}/dataRetentionSettings"
s = client.get_data_retention_settings(name=name)
ok = (s.event_data_retention == REQUIRED
and s.reset_user_data_on_new_activity)
status = "OK" if ok else "DRIFT"
print(status, prop.display_name, prop.property,
s.event_data_retention.name,
s.reset_user_data_on_new_activity)Here prop.property is already in the form properties/123456789, so you can build the resource name by appending the path. You can run this on a schedule and send the DRIFT lines to whoever owns the policy. That connects directly to the final chapter on auditing a property against a privacy policy.
Common errors
| Status | Typical cause | Fix |
|---|---|---|
| 400 | Missing `updateMask`, or a value your property type does not allow, such as `FIFTY_MONTHS` on a standard property. | Add the mask. Use `TWO_MONTHS` or `FOURTEEN_MONTHS` unless the property is Analytics 360. |
| 401 | Expired or malformed token. | Request a new access token. |
| 403 | The Admin API is not enabled in the Cloud project, the scope is read-only, or the identity lacks the Editor role. | Enable the API, request `analytics.edit`, and check the role on the property. |
| 404 | Wrong property ID, such as a measurement ID or account ID. | Use the numeric property ID. |
Things to remember before changing a value
- Shortening retention is a one-way action in practice. Data older than the new period is deleted, and lengthening the setting later does not bring it back. Export history to BigQuery first if you may need it.
- The setting covers user-level event data used by Explorations and some audience and segment features. Standard aggregated reports are not affected, as the earlier chapters explain.
- Always read the settings back after a PATCH. The response confirms what was stored, and a comparison step in your script catches mask mistakes.
Exercise
A script sends a PATCH to dataRetentionSettings with the body {"eventDataRetention":"FOURTEEN_MONTHS","resetUserDataOnNewActivity":true} but with updateMask=eventDataRetention only. The call returns 200. What happens to resetUserDataOnNewActivity, and how would you confirm it?
Show answer
The field is not in the mask, so the API ignores it and the stored value stays as it was before. Only eventDataRetention changes. To confirm, send a GET to the same resource and compare both fields with what you intended. To fix it, add resetUserDataOnNewActivity to the mask, giving updateMask=eventDataRetention,resetUserDataOnNewActivity.
Exercise
You get a 400 error when setting eventDataRetention to THIRTYEIGHTMONTHS on a property. The request has a valid token and a correct updateMask. What is the most likely cause?
Show answer
The property is a standard property, which accepts only TWOMONTHS and FOURTEENMONTHS. Longer periods are available only on Analytics 360 properties. Use FOURTEEN_MONTHS, or move the property to 360 if you need a longer period.