Digital analysts often face time-consuming tasks daily. Creating and managing custom definitions can be particularly tedious, especially for agencies or consultants handling multiple accounts and properties.
In this article, I’ll guide you through creating custom definitions using the GA4 Admin API.
What is the GA4 Admin API?
Understanding Custom Definitions in GA4
If you’ve used GA4 or any out-of-the-box analytics tool, adding custom definitions is likely familiar. For those new to the concept, think of custom definitions as columns in a table. An interaction, like a click on a screen, is the primary event, but it lacks context without additional data. Parameters like Clicked Text
or Click URL
provide insight into the interaction and its context.
The event name serves as the primary column, while other details about the interaction are secondary parameters that add necessary context for analysis.
Scopes of Custom Definitions and Their Uses
Custom definitions in GA4 have different scopes, much like columns holding distinct data types. The following diagram illustrates the four primary scopes:
%%{init: {'theme': 'base', 'themeVariables': { 'background': '#1F2020', 'primaryColor': '#272A36', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#272A36', 'lineColor': '#ffffff', 'secondaryColor': '#272A36', 'tertiaryColor': '#272A36', 'fontSize': '12px' }}}%% graph TB A[GA4 Scopes] --> U[User Scope] U --> U1[~90 days window] U --> U2[User metrics only] A --> S[Session Scope] S --> S1[Single visit] S --> S2[Session metrics only] A --> E[Event Scope] E --> E1[Single action] E --> E2[Event metrics only] A --> I[Item Scope] I --> I1[Product-level data] I --> I2[Item metrics only] A --> R[Reporting Rules] R --> R1[Match scopes] R --> R2[Avoid mixing scopes]
GA4 offers four primary scopes for custom definitions. The best analogy for these scopes is a pyramid hierarchy:
User Scope
This is the broadest scope, covering all user interactions within a 90-day look-back window. It captures the entire user journey across multiple sessions.
For attribution, user scope uses a first-click model, crediting the initial touchpoint that brought the user to the site or app for conversions.
Session Scope
This scope focuses on a single session, defined as user interactions within a timeframe (typically 30 minutes). It uses a last non-direct click attribution model, crediting the last non-direct interaction before a conversion.
Session scope is useful for analyzing behavior during individual visits, such as session duration or bounce rates.
Event Scope
Event scope focuses on individual user actions, such as page views, clicks, or conversions. It uses the property-level attribution model, configurable to settings like data-driven or last-click.
This scope is essential for detailed event-level analysis, providing more context for each interaction. For e-commerce, note that the Transactions metric is unavailable; instead, use Conversions with a filter for purchase events.
Item Scope
Specific to e-commerce, item scope focuses on individual products within transactions, capturing data like item names, brands, and revenues. Robust e-commerce tracking is essential for detailed sales analysis.
This scope is less relevant for non-e-commerce sites. If a parameter is missing from e-commerce events (e.g., brand data), it’s likely due to a misconfigured Google Tag Manager (GTM) setup or an absent parameter in the data layer.
Creating a New Scope Using the GA4 Admin API
The GA4 Admin API allows you to create custom definitions with appropriate scopes without relying on the GA4 interface.
Prerequisites
- Python 3.x installed.
- Required libraries installed:
pip install google-api-python-client google-auth
To proceed, you need a service account with access to your GA4 property. Refer to our guide on creating a service account.
The process follows this flow:
%%{init: {'theme': 'base', 'themeVariables': { 'background': '#1F2020', 'primaryColor': '#272A36', 'primaryTextColor': '#ffffff', 'primaryBorderColor': '#272A36', 'lineColor': '#ffffff', 'secondaryColor': '#272A36', 'tertiaryColor': '#272A36' }}}%% graph LR A[Load Service Account JSON Credentials] --> B[Create Credentials Object] B --> C[Build GA4 Analytics Data API Client] C --> D[Define Request Parameters] D --> E[Send API Request to GA4 Analytics Data API] E --> F[Receive API Response with Data] F --> G[Parse & Process Data] G --> H[Use Data for Analysis or Reporting]
It begins with setting up a service account in Google Cloud, downloading the JSON key, and granting it access to your GA4 property. This enables secure authentication without manual login via the GA4 interface.
Setting Up the Connection
We covered this process in our GA4 Admin API introduction. Once authenticated, your script builds a client for the GA4 Admin API and defines parameters for the API call, such as the property ID and custom definition configuration.
What is a Client in the Context of the GA4 API?
Creating a Custom Definition: Python Script Overview
Step 1: Import Required Libraries
import json from google.oauth2 import service_account from googleapiclient.discovery import build
These imports provide the tools needed:
json
: Handles data formats (useful for parsing).
google.oauth2.service_account
: Authenticates using a service account.
googleapiclient.discovery
: Communicates with the GA4 Admin API.
These are the building blocks for secure interaction with Google services.
Step 2: Load the Service Account Credentials
credentials = service_account.Credentials.from_service_account_file( 'path_to_your_service_account_key.json', scopes=['https://www.googleapis.com/auth/analytics.edit'] )
This loads your service account key (a .json
file from Google Cloud) and grants permission to edit Analytics settings.
The analytics.edit scope allows creating custom definitions. Ensure your GA4 property has granted access to this service account.
Step 3: Initialize the GA4 Admin API Client
analytics_admin = build('analyticsadmin', 'v1beta', credentials=credentials)
This creates a client for the Admin API, enabling commands like creating a new custom definition.
‘analyticsadmin’ is the API name, and ‘v1beta’ is the version. Beta versions may change, so check Google’s documentation.
Step 4: Set Your GA4 Property ID
Replace 'YOUR_GA4_PROPERTY_ID'
with your GA4 property ID (found in the Admin section of GA4. Browse to administration > Property details and copy the Id in the upper right corner).

This ID links your script to the correct Analytics property.
Step 5: Define the Custom Definition
custom_dimension = { 'parameterName': 'custom_param', 'displayName': 'Custom Parameter', 'description': 'Description of custom parameter', 'scope': 'EVENT' # Can be 'USER', 'EVENT', or 'ITEM' }
This defines the custom definition:
parameterName
: The exact name sent in your event (must match your tagging setup).
displayName
: The name shown in the GA4 interface.
description
: Optional, but clarifies the dimension’s purpose.
scope
: Specifies the level (Event, User, or Item).
Ensure the parameter name matches what your site or app sends to GA4 to collect data correctly.
Step 6: Create the Custom Definition
response = analytics_admin.properties().customDimensions().create( parent=f'properties/{property_id}', body=custom_dimension ).execute()
This sends the API request to create the custom definition in the specified GA4 property.
The parent specifies the property, and body contains the dimension details defined earlier.
Step 7: Print the Result
print(f"Created custom definition: {response['name']}")
If successful, this confirms the custom definition was created and displays its identifier.