The Google Analytics 4 (GA4) Data API offers programmatic access to the rich datasets collected by Google Analytics 4 properties. This guide provides an expert-level, detailed examination of the dimensions and metrics available through this API, their calculation, scope, compatibility, and practical application in building sophisticated analytical reports. It is intended for technical data analysts and developers seeking to leverage the full power of their GA4 data programmatically.
I. Introduction to the GA4 Data API
The Google Analytics 4 Data API serves as a crucial interface for developers and data analysts, enabling programmatic access to GA4 report data.1 This capability extends beyond the standard GA4 user interface, offering enhanced customization and flexibility in data retrieval. The API is engineered to support the creation of custom applications, the automation of reporting workflows, and the integration of GA4 data with other business intelligence systems and platforms.3 A core strength of the API is its support for querying both predefined and custom dimensions and metrics, providing a comprehensive toolkit for in-depth analysis.1
The API's architecture includes several key methods for data retrieval. The runReport method is the primary mechanism for what is termed "core reporting," which mirrors the general reporting functionalities found within the Google Analytics UI.2 Beyond this, the Data API v1 also provides specialized methods for Realtime reporting and Funnel reporting, catering to diverse analytical needs.2 The availability of these distinct reporting methods indicates a structured approach by Google to provide various types of analytical data programmatically, acknowledging that advanced users often require access beyond the confines of a graphical interface. This is particularly relevant given GA4's event-based data model, which captures granular user interactions and generates vast datasets that can be more effectively harnessed through an API.5
A. The Role of Dimensions and Metrics in API Reporting
At the heart of any analytical query, whether executed through a user interface or an API, lie dimensions and metrics. These elements are fundamental to structuring data requests and interpreting the resulting reports.
Dimensions are qualitative attributes that categorize data, providing context for meaningful analysis.1 They answer questions like "who," "what," "where," "when," and "how." Examples of dimensions include geographical indicators like city, user interaction descriptors like eventName, or content attributes like pageTitle. When constructing an API request, the specific "API Name" of the desired dimension must be used to ensure precise data retrieval.1 The runReport method, for instance, supports the inclusion of up to nine dimensions in a single request, allowing for multifaceted data segmentation.2
Metrics, conversely, are quantitative measurements of data.1 They represent numerical values such as sums, ratios, or counts, quantifying the characteristics described by dimensions. Common metrics include activeUsers (number of engaged users), sessions (number of user visits), and purchaseRevenue (monetary value of purchases). Similar to dimensions, the "API Name" of a metric is specified in API requests.1
In essence, reports generated via the API are structured as tables. Dimensions typically define the rows or act as grouping criteria, while metrics provide the numerical values associated with those groupings.2 This programmatic approach to requesting dimensions and metrics offers greater control and automation compared to manual report generation, allowing for the development of sophisticated data-driven applications.
B. Understanding Data Scopes (User, Session, Event, Item)
A critical concept for accurate data interpretation and reporting in Google Analytics 4 is "scope." GA4 data is organized hierarchically, with dimensions and metrics being defined at specific levels of this hierarchy: User, Session, Event, and Item.7 Understanding these scopes is paramount, as incorrectly combining elements from different scopes can lead to misleading or nonsensical data, even if the API technically permits the query.7
The scopes are defined as follows:
User Scope: Attributes at this level relate to the user across all their sessions and interactions. These dimensions often describe characteristics of the user themselves or their initial engagement with the site or app. Examples include demographic information like userAgeBracket and userGender, or first-touch attribution dimensions like firstUserDefaultChannelGroup.1 A user-scoped dimension's value typically persists for that user over time.
Session Scope: These attributes pertain to a single visit or session by a user. All events within a particular session will share the same session-scoped dimensional values. Examples include sessionCampaignName, sessionDefaultChannelGroup, sessionMedium, and sessionSource.1 These are crucial for analyzing traffic sources and campaign performance for individual visits.
Event Scope: This is the most granular scope, with attributes relating to individual interactions or logged events. Each event carries its own set of event-scoped dimension values. Examples include eventName, pagePath, and the parameters associated with specific events.1 Given GA4's event-based model, a significant portion of data analysis revolves around event-scoped data.5
Item Scope: This scope is specific to e-commerce and relates to attributes of individual products or services within e-commerce events like add_to_cart or purchase. Examples include itemName, itemId, and itemCategory.1
Custom dimensions can be defined at the User, Event, or Item scope, while custom metrics are always event-scoped.1 The hierarchical nature (User > Session > Event > Item) implies that data from lower scopes can roll up to higher scopes. For instance, event data contributes to session data, and session data contributes to user data.
The significance of scope compatibility cannot be overstated. A common guideline, often referred to as a "golden rule," is that reports should ideally combine dimensions and metrics belonging to the same scope, or metrics from a scope lower than or equal to the dimension's scope.7 For example, combining a session-scoped dimension like sessionCampaignName with a user-scoped metric like totalUsers can be problematic. The interpretation of totalUsers in this context becomes ambiguous: does it count users whose first session had that campaign name, or users who had any session with that campaign name? Such combinations can lead to misattribution or inflated counts if not handled with a clear understanding of how GA4 processes these queries.8 The API documentation itself lists dimensions that clearly belong to different scopes (e.g., userId vs. sessionId vs. pageTitle vs. itemName), underscoring the need for careful selection by the developer or analyst.1
II. GA4 API Dimensions: The Definitive Guide
Dimensions are the bedrock of contextual analytics, providing the "who, what, where, when, and how" for the numerical data represented by metrics. The GA4 Data API offers a rich set of standard dimensions and allows for the querying of custom dimensions defined within a property.
A. Understanding DimensionMetadata
To programmatically discover and understand the dimensions available for a specific GA4 property, the properties.getMetadata API method is employed. This method returns an array of DimensionMetadata objects, each providing comprehensive details about a single dimension.14 This metadata is crucial for developers building dynamic reporting tools or applications that need to adapt to the specific configuration of a GA4 property.
The key fields within a DimensionMetadata object include 15:
apiName: This string is the programmatic identifier for the dimension and is the value used when specifying dimensions in API requests (e.g., eventName, city).
uiName: This string represents the user-friendly name of the dimension as it appears in the Google Analytics user interface (e.g., "Event name", "City"). This is useful for displaying dimension choices to end-users.
description: A textual description explaining how the dimension is used and how its values are calculated or populated. This provides essential context for understanding the dimension's meaning.
deprecatedApiNames: An array of strings listing any older API names that were previously used for this dimension. While these deprecated names might still be usable for a transitional period, the current apiName should be preferred for new development.
customDefinition: A boolean flag that is true if the dimension is a custom dimension (user-scoped, event-scoped, or item-scoped) or a custom channel group specific to the property. This allows for easy differentiation between standard and property-specific dimensions.
category: A string representing the display name of the category to which this dimension belongs (e.g., "User", "Session", "E-commerce", "Attribution", "Demographics"). Similar dimensions and metrics are often grouped under the same category, providing a thematic organization.15
The DimensionMetadata serves as the API's self-description mechanism. While it provides a category field that often aligns with the dimension's scope (e.g., "Demographics" dimensions are typically user-scoped), an explicit "scope" field is not directly part of the DimensionMetadata for standard dimensions.1 For standard dimensions, scope is generally inferred from established naming conventions (e.g., prefixes like session..., firstUser...), the dimension's category, or its detailed description. This makes careful examination of the metadata and documentation essential for correct scope identification.
B. Master Table of Standard Dimensions
The following table provides a comprehensive list of commonly used standard dimensions available through the GA4 Data API, including their API Name, UI Name, Description, general Category, and Deduced Scope. This information is primarily compiled from the API schema documentation and related resources.1 The "Deduced Scope" is inferred based on naming conventions, category, and descriptive information.
Note: This table represents a selection of common dimensions. For the absolute complete and most current list for a specific property, the properties.getMetadata API method should be used. The "Category" and "Deduced Scope" are based on common interpretations and official documentation structure; some dimensions might have nuanced scoping depending on the context of other dimensions and metrics in a query.
API Name | UI Name | Description | Category | Deduced Scope |
achievementId | Achievement ID | The achievement ID in a game for an event. Populated by the event parameter achievement_id. | Game | Event |
adFormat | Ad format | Describes the way ads looked and where they were located. Typical formats include Interstitial, Banner, Rewarded, and Native advanced. | Advertising | Event |
adSourceName | Ad source | The source network that served the ad. | Advertising | Event |
appVersion | App version | The app's versionName (Android) or short bundle version (iOS). | Platform / Device | Event |
audienceName | Audience name | The given name of an Audience. Users are reported in the audiences to which they belonged during the report's date range. | Audience | User |
browser | Browser | The browsers used to view your website. | Platform / Device | Session/Event |
campaignId | Campaign ID | The identifier of the marketing campaign. Present only for key events. Includes Google Ads Campaigns, Manual Campaigns, & other Campaigns. | Attribution | Event |
campaignName | Campaign | The name of the marketing campaign. Present only for key events. | Attribution | Event |
city | City | The city from which the user activity originated. | Geography | User/Session |
contentGroup | Content Group | The content group a user interacted with. | Content | Event |
country | Country | The country from which user activity originated. | Geography | User/Session |
date | Date | The date of an event in YYYYMMDD format. | Time | Event |
dayOfWeekName | Day of Week Name | The name of the day of the week. | Time | Event |
defaultChannelGroup | Default Channel Group | The default channel group that acquired the user/session/event. | Attribution | Event |
deviceCategory | Device Category | The type of device: Desktop, Mobile, or Tablet. | Platform / Device | User/Session |
eventName | Event name | The name of the event. | Event | Event |
firstUserCampaignName | First user campaign | The campaign that first acquired the user. | Attribution | User |
firstUserDefaultChannelGroup | First user default channel group | The default channel group that first acquired the user. | Attribution | User |
firstUserMedium | First user medium | The medium that first acquired the user. | Attribution | User |
firstUserSource | First user source | The source that first acquired the user. | Attribution | User |
fullPageUrl | Full page URL | The hostname, page path, and query string for web pages visited - does not contain the protocol. | Content | Event |
hour | Hour | The hour of the day (00-23) for an event. | Time | Event |
itemBrand | Item brand | The brand of an e-commerce item. Populated by the item_brand parameter. | E-commerce | Item |
itemCategory | Item category | The category of an e-commerce item. Populated by the item_category parameter. | E-commerce | Item |
itemId | Item ID | The ID of an e-commerce item. Populated by the item_id parameter. | E-commerce | Item |
itemName | Item name | The name of an e-commerce item. Populated by the item_name parameter. | E-commerce | Item |
landingPage | Landing page + query string | The page path and query string associated with the first pageview in a session. | Content | Session |
language | Language | The language setting of the user's device. | Demographics | User |
medium | Medium | The medium associated with an event or that referred users. | Attribution | Event |
month | Month | The month of the year (01-12). | Time | Event |
newVsReturning | New / returning | Identifies users as 'new' or 'returning'. | User | User |
operatingSystem | Operating system | The operating system of the user's device. | Platform / Device | User/Session |
orderCoupon | Order coupon | The coupon code used for an order. Populated by the coupon parameter at the event level for purchase events. | E-commerce | Event |
pageLocation | Page location | The full URL (including protocol, hostname, page path, and query string) of the page. | Content | Event |
pagePath | Page path | The path part of the page URL (e.g., /directory/page.html). Does not include query string. | Content | Event |
pageReferrer | Page referrer | The full referring URL for a pageview. | Content | Event |
pageTitle | Page title | The title of the page. | Content | Event |
platform | Platform | The platform on which the user activity occurred (Web, iOS, Android). | Platform / Device | User/Session |
screenResolution | Screen resolution | The screen resolution of the user's device. | Platform / Device | User/Session |
sessionCampaignName | Session campaign | The campaign name that led to a session. | Attribution | Session |
sessionDefaultChannelGroup | Session default channel group | The default channel group that led to a session. | Attribution | Session |
sessionId | Session ID | The unique identifier for a session. | Session | Session |
sessionMedium | Session medium | The medium that led to a session. | Attribution | Session |
sessionSource | Session source | The source that led to a session. | Attribution | Session |
signedInWithUserId | Signed in with user ID | Returns 'Yes' if the user was signed in with User-ID, 'No' otherwise. | User | User |
source | Source | The source associated with an event or that referred users. | Attribution | Event |
sourceMedium | Source / Medium | The combined source and medium. | Attribution | Event |
transactionId | Transaction ID | The unique identifier for an e-commerce transaction. Populated by the transaction_id parameter. | E-commerce | Event |
userAgeBracket | Age | The age bracket of the user (e.g., '18-24', '25-34'). Requires Google Signals activation. | Demographics | User |
userGender | Gender | The gender of the user. Requires Google Signals activation. | Demographics | User |
userId | User ID | The User ID assigned if using the User-ID feature. | User | User |
year | Year | The year of an event. | Time | Event |
This master table serves as a foundational reference. The "Deduced Scope" and "Category" provide essential context for report building and ensuring compatibility. For instance, dimensions prefixed with firstUser... are user-scoped and describe the initial acquisition of the user, while session... dimensions are session-scoped, describing attributes of a specific visit.9 E-commerce dimensions like itemName are item-scoped and are populated from parameters within the items array of e-commerce events.1
C. Dimensions by Category/Deduced Scope (with detailed explanations)
Grouping dimensions by their category or deduced scope aids in understanding their typical use cases and how they are populated.
1. User Dimensions
These dimensions provide context about users, often reflecting their first interaction or demographic characteristics. Examples include userId, firstUserDefaultChannelGroup, userAgeBracket, userGender, and newVsReturning.1 Dimensions prefixed with firstUser... are particularly valuable for analyzing initial user acquisition channels, helping to understand which marketing efforts are most effective at bringing new users to the platform.19 For instance, firstUserSource indicates the original source that led to the user's first visit.
2. Session Dimensions
Session-scoped dimensions describe the attributes of a single user visit or session. These are crucial for traffic analysis and evaluating campaign performance within specific visits. Examples include sessionId, sessionCampaignName, sessionDefaultChannelGroup, sessionMedium, and sessionSource.1 For example, sessionSourceMedium would indicate the source and medium for a particular session, which might differ from the firstUserSourceMedium if the user returned via a different channel.
3. Traffic Source Dimensions
This broad category includes dimensions that provide detailed information about how users arrive at the website or application. These can be event-scoped (e.g., source, medium associated with a specific key event), session-scoped (e.g., sessionSource, sessionDefaultChannelGroup), or user-scoped (e.g., firstUserSource, firstUserDefaultChannelGroup).1 The API schema lists numerous traffic source dimensions, including those related to integrated advertising platforms like Google Ads, Campaign Manager 360, Display & Video 360, and Search Ads 360.1 These dimensions are populated through auto-tagging, manual UTM tagging, or integration links.
4. Content Dimensions
These dimensions describe the content with which users interact. Key examples are pageTitle, pagePath, pageLocation, landingPage, and contentGroup.1 It's important to understand the nuances between similar dimensions; for example, pagePath typically represents the path portion of a URL (e.g., /category/product.html) and does not include query parameters, making it useful for aggregating views of the same page regardless of URL parameters. In contrast, pageLocation provides the full URL, including protocol, hostname, path, and query string.21 landingPage refers to the first page viewed in a session.
5. Technical Dimensions
Technical dimensions provide context about the user's device, browser, and network environment. Common examples include browser, operatingSystem, deviceCategory (Desktop, Mobile, Tablet), platform (Web, iOS, Android), and screenResolution.1 This information is vital for understanding user experience across different technologies and optimizing for specific environments.
6. Date & Time Dimensions
These dimensions are essential for time-based analysis, trend identification, and cohort analysis. The API provides a granular set of time dimensions, such as date, year, month, day, hour, minute, and dayOfWeekName.1 An extensive list of time-related dimensions, including variations for week numbering (US vs. ISO) and nth-period dimensions (e.g., nthDay, nthMonth), can be found in resources like 22, enabling highly specific temporal segmentation.
7. E-commerce Dimensions
Crucial for businesses selling products or services online, e-commerce dimensions provide details about products, transactions, and promotions. Many of these are item-scoped, such as itemName, itemId, itemCategory, and itemBrand. Others, like transactionId and orderCoupon, are event-scoped and associated with purchase or checkout events.1 These dimensions are populated from specific parameters sent with e-commerce events (e.g., item_name parameter populates the itemName dimension).20
8. Game Dimensions
For applications that are games, specific dimensions like level (player's current level), character (player character), and achievementId (ID of an achievement unlocked) are available.1 These are populated from corresponding event parameters.
9. Other Specialized Dimensions
The API also includes dimensions for more specific analytical needs, such as adFormat and adSourceName for advertising analysis, or audienceName for reporting on defined user audiences.1
Understanding how each dimension is populated is key to ensuring accurate data collection and subsequent analysis. For instance, traffic source dimensions rely on proper UTM tagging or ad platform integrations, while e-commerce dimensions require correct implementation of e-commerce event tracking with all necessary parameters.
III. GA4 API Metrics: Comprehensive Reference
Metrics are the quantitative heart of analytics, providing the numerical measurements that, when combined with dimensions, yield insights. The GA4 Data API offers a wide array of standard metrics and supports querying custom metrics.
A. Understanding MetricMetadata (including Type and Expression)
Similar to dimensions, the properties.getMetadata API method returns MetricMetadata objects for each metric available to a GA4 property.14 This metadata is essential for understanding the nature, calculation, and potential limitations of each metric.
Key fields within a MetricMetadata object include 16:
apiName: The programmatic identifier for the metric used in API requests (e.g., eventCount, sessions).
uiName: The user-friendly name of the metric as displayed in the Google Analytics UI (e.g., "Event count", "Sessions").
description: A textual explanation of how the metric is used and, importantly, how it is calculated.
deprecatedApiNames: An array of strings listing any older, deprecated API names for the metric.
type: An enum value of type MetricType that indicates the data type of the metric's values. Common types include TYPE_INTEGER, TYPE_FLOAT, TYPE_CURRENCY, TYPE_SECONDS, TYPE_MILLISECONDS, and TYPE_PERCENT.24 The type dictates how the metric data should be formatted, interpreted, and used in further calculations.
expression: A string containing the mathematical formula used to calculate derived metrics. For metrics that are not derived (i.e., direct counts or sums), this field is typically empty. When present, this expression can be used in the expression field of a Metric object in an API request to achieve equivalent reporting.16 For example, a metric like averageEngagementTimePerSession might have an expression such as userEngagementDuration/sessions.26
customDefinition: A boolean flag that is true if the metric is a custom metric defined for the property.
blockedReasons: An array of enum values (from BlockedReason) explaining why access to this metric might be blocked for the requesting property or user. Reasons can include NO_REVENUE_METRICS or NO_COST_METRICS if the property or user has restrictions on viewing such data.24 If this field is populated, API requests for the metric might still succeed, but the report will contain zeros for that metric. Metric filters on blocked metrics will cause requests to fail.
category: A string representing the display name of the category to which this metric belongs (e.g., "User", "Engagement", "E-commerce"). This helps in organizing and finding related metrics.
The MetricMetadata provides a wealth of information crucial for developers. The type field guides data handling, while the expression field demystifies the calculation of complex or ratio-based metrics. The blockedReasons field offers practical, preemptive information about potential data access limitations, which can prevent confusion when a metric returns unexpected zero values.
B. Master Table of Standard Metrics
The following table provides a comprehensive list of commonly used standard metrics available through the GA4 Data API, including their API Name, UI Name, Description, general Category, Data Type, and a summary of their calculation or the expression if it's a derived metric. This information is primarily compiled from the API schema documentation and related resources.1
Note: This table represents a selection of common metrics. For the absolute complete and most current list for a specific property, the properties.getMetadata API method should be used. The "Calculation Summary / Expression" is based on official descriptions or common understanding; complex metrics might have more nuanced calculations internally.
API Name | UI Name | Description | Category | Type (MetricType) | Calculation Summary / Expression |
active1DayUsers | 1-day active users | The number of distinct active users on a single day. | User | TYPE_INTEGER | Count of unique users with engagement on the given day. |
active7DayUsers | 7-day active users | The number of distinct active users within a 7-day period. | User | TYPE_INTEGER | Count of unique users with engagement in the preceding 7 days. |
active28DayUsers | 28-day active users | The number of distinct active users within a 28-day period. | User | TYPE_INTEGER | Count of unique users with engagement in the preceding 28 days. |
activeUsers | Active users | The number of distinct users who had an engaged session or specific first interaction events. | User | TYPE_INTEGER | See Section III.C.1 for detailed calculation. |
addToCarts | Adds to cart | The number of times items were added to a shopping cart. | E-commerce | TYPE_INTEGER | Sum of add_to_cart events or quantities from items array in add_to_cart events. |
advertiserAdClicks | Ad Clicks | The total number of clicks on your ads (e.g., Google Ads). Requires linked ad account. | Advertising | TYPE_INTEGER | Sum of clicks from linked advertising platforms. |
advertiserAdCost | Ad Cost | The total cost of your advertising campaigns. Requires linked ad account. | Advertising | TYPE_CURRENCY | Sum of cost from linked advertising platforms. |
averagePurchaseRevenue | Average purchase revenue | The average revenue per purchase transaction. | E-commerce | TYPE_CURRENCY | purchaseRevenue / ecommercePurchases |
averageSessionDuration | Average session duration | The average duration of sessions in seconds. | Engagement | TYPE_SECONDS | userEngagementDuration / sessions (or similar based on total session time). |
cartToViewRate | Cart-to-view rate | The rate at which items viewed are added to cart. | E-commerce | TYPE_PERCENT | addToCarts / itemsViewed (or relevant view metric). |
checkouts | Checkouts | The number of times users initiated the checkout process. | E-commerce | TYPE_INTEGER | Sum of begin_checkout events or quantities. |
cohortActiveUsers | Cohort Active Users | Active users belonging to a specific cohort. | Cohort | TYPE_INTEGER | Count of active users within a defined cohort. |
ecommercePurchases | Ecommerce purchases | The total number of e-commerce purchase transactions. | E-commerce | TYPE_INTEGER | Count of purchase events. |
engagedSessions | Engaged sessions | The number of sessions that lasted 10 seconds or longer, OR had 1+ key events, OR had 2+ page/screen views. | Engagement | TYPE_INTEGER | See Section III.C.2 for detailed definition. |
engagementRate | Engagement rate | The percentage of sessions that were engaged sessions. | Engagement | TYPE_PERCENT | (engagedSessions / sessions) * 100 |
eventCount | Event count | The total number of events recorded. | Event | TYPE_INTEGER | Sum of all events. |
eventCountPerUser | Event count per user | The average number of events per user. | Event | TYPE_FLOAT | eventCount / totalUsers (or activeUsers). |
firstTimePurchasers | First-time purchasers | The number of users who made their first purchase. | E-commerce | TYPE_INTEGER | Count of users with their first purchase event. |
grossItemRevenue | Gross Item Revenue | Total revenue from items before discounts. | E-commerce | TYPE_CURRENCY | Sum of (item price * quantity) for all purchased items. |
grossPurchaseRevenue | Gross Purchase Revenue | Total revenue from purchases before refunds, including tax and shipping. | E-commerce | TYPE_CURRENCY | Sum of value parameter from purchase events. |
itemDiscountAmount | Item Discount Amount | The total monetary value of discounts applied to items. | E-commerce | TYPE_CURRENCY | Sum of discount parameter from items array in e-commerce events. |
itemRefundAmount | Item Refund Amount | The total monetary value of refunds for items. | E-commerce | TYPE_CURRENCY | Sum of item-level refund amounts. |
itemRevenue | Item revenue | Total revenue from items only (price x quantity), excluding tax and shipping. | E-commerce | TYPE_CURRENCY | Sum of (price * quantity) from items array in purchase events. |
itemsPurchased | Items purchased | The total number of units of items purchased. | E-commerce | TYPE_INTEGER | Sum of quantity from items array in purchase events. |
itemsViewed | Item Views | The number of times items were viewed. | E-commerce | TYPE_INTEGER | Sum of view_item events or quantities from items array in view_item events. |
keyEvents | Key Events | The total number of key events (formerly conversions) recorded. | Event | TYPE_INTEGER | Sum of all events marked as key events. |
newUsers | New users | The number of users who interacted with your site or app for the first time. | User | TYPE_INTEGER | Count of users logging first_visit or first_open event. |
purchaseRevenue | Purchase revenue | Total revenue from e-commerce purchases. Includes tax and shipping if sent, minus refunds. | E-commerce | TYPE_CURRENCY | Sum of value from purchase events, adjusted for refund events. |
purchaseToViewRate | Purchase-to-view rate | The rate at which item views result in purchases. | E-commerce | TYPE_PERCENT | ecommercePurchases / itemsViewed (or relevant view metric). |
returnOnAdSpend | Return On Ad Spend | The revenue generated for every dollar spent on advertising. | Advertising | TYPE_FLOAT | totalAdRevenue / advertiserAdCost. |
screenPageViews | Views | The total number of app screens or web pages users viewed. Repeated views of a single page/screen are counted. | Engagement | TYPE_INTEGER | Sum of page_view and screen_view events. |
screenPageViewsPerSession | Views per session | The average number of pages or screens viewed per session. | Engagement | TYPE_FLOAT | screenPageViews / sessions. |
sessionKeyEventRate:EVENT_NAME | Session key event rate (event_name) | The percentage of sessions in which a specific key event occurred. | Event | TYPE_PERCENT | (Sessions with EVENT_NAME / Total sessions) * 100. |
sessions | Sessions | The total number of sessions. | Engagement | TYPE_INTEGER | Count of session_start events. |
sessionsPerUser | Sessions per user | The average number of sessions per user. | Engagement | TYPE_FLOAT | sessions / totalUsers (or activeUsers). |
totalAdRevenue | Total ad revenue | The total revenue from ads displayed on your site/app (e.g., AdMob). | Advertising | TYPE_CURRENCY | Sum of ad_impression event values. |
totalUsers | Total users | The total number of unique users who logged any event. | User | TYPE_INTEGER | Count of distinct user identifiers. |
userEngagementDuration | User engagement duration | The total amount of time (in seconds) your website or app was in the foreground of users' devices. | Engagement | TYPE_SECONDS | Sum of engagement_time_msec parameter values (converted to seconds). |
userKeyEventRate:EVENT_NAME | User key event rate (event_name) | The percentage of users who triggered a specific key event. | Event | TYPE_PERCENT | (Users who triggered EVENT_NAME / Total users) * 100. |
This master table of metrics, complemented by their types and calculation summaries, is vital for developers. It ensures that the data retrieved is correctly understood and processed. For example, knowing a metric is TYPE_CURRENCY implies it should be formatted with appropriate currency symbols and decimal places, while a TYPE_SECONDS metric might need conversion to minutes or hours for better readability. The calculation summary for derived metrics like engagementRate or averageSessionDuration clarifies their meaning beyond just the name.
C. Metrics by Category (with detailed explanations and calculation logic)
Understanding metrics within their categorical groupings provides further clarity on their purpose and calculation.
1. User Metrics
These metrics quantify aspects of your user base.
activeUsers: This is a cornerstone metric in GA4, representing the number of distinct users who engaged with your site or app.1 A user is considered active if they have an "engaged session" (defined below) or if Analytics collects specific first-time interaction events (first_visit for web, first_open for apps) along with the engagement_time_msec parameter.29 This definition makes activeUsers a more qualified measure of audience size than simply counting all users.
newUsers: This metric counts the number of users who interacted with your site or app for the very first time during the specified date range, identified by logging the first_visit (web) or first_open (app) event.29
totalUsers: This represents the total number of unique users who logged any event during the specified date range.29 It's important to distinguish totalUsers from activeUsers; totalUsers can include users who did not meet the engagement criteria for being "active".29
active1DayUsers, active7DayUsers, active28DayUsers: These provide rolling active user counts over specific short-term windows, useful for tracking daily, weekly, and monthly engagement trends.1
2. Engagement Metrics
Engagement metrics measure how users interact with your content and platform.
sessions: The total number of sessions that began on your website or application.1 A session typically starts when a user opens your app in the foreground or views a page/screen and no other session is currently active.
engagedSessions: A session is counted as engaged if it meets at least one of the following criteria: lasts 10 seconds or longer, OR includes one or more key events (conversions), OR includes two or more page or screen views.1 This metric helps filter out bounces or very brief, non-interactive visits.
engagementRate: Calculated as (engagedSessions / sessions) * 100.1 This percentage indicates the proportion of sessions where users showed meaningful interaction.
averageSessionDuration: The average length of a session, typically calculated by dividing the total duration of all sessions by the total number of sessions.35 In GA4, this is often closely related to userEngagementDuration / sessions.
screenPageViews (often referred to as "Views"): The total number of app screens or web pages viewed. Repeated views of a single screen or page are counted.1
userEngagementDuration: The total cumulative time (typically in seconds or milliseconds) that your app was in the foreground of a user's device or your website was the active tab in their browser.1 This is a key component in many engagement calculations.
3. E-commerce Metrics
These metrics are vital for businesses selling goods or services online.
ecommercePurchases: The total number of purchase transactions that occurred.1
purchaseRevenue: The total monetary value from e-commerce transactions. This typically includes tax and shipping if those values are passed in the purchase event and is net of refunds.1
averagePurchaseRevenue: Calculated as purchaseRevenue / ecommercePurchases, giving the average value per transaction.1
itemsPurchased: The total number of individual units of items sold.1 This is populated from the quantity parameter within the items array of purchase events.
addToCarts: The number of times items were added to a shopping cart.1
itemRevenue: The total revenue generated from the sale of items only, specifically calculated as the sum of (price × quantity) for each item. This metric explicitly excludes tax and shipping.1 It is populated from the price and quantity parameters in the items array of purchase events.
It's important to note that some e-commerce metrics, such as itemsViewed and addToCarts, began populating data only from September 8, 2022. Reports including dates prior to this may show inconsistent data for these specific metrics.20
4. Advertising Metrics
These metrics track the performance of advertising campaigns and monetization through ads.
advertiserAdClicks: The number of clicks on your ads, typically requiring integration with platforms like Google Ads.1
advertiserAdCost: The total amount spent on your advertising campaigns.1
advertiserAdCostPerClick: The average cost for each ad click (advertiserAdCost / advertiserAdClicks).1
totalAdRevenue: Revenue generated from ads displayed on your property (e.g., via AdMob).1
returnOnAdSpend: A key performance indicator calculated as totalAdRevenue / advertiserAdCost.1
5. Event Metrics
These metrics focus on the occurrence and value of specific events.
eventCount: The total number of times any event was triggered.1
eventCountPerUser: The average number of events triggered per user.1
keyEvents: The total number of events that have been marked as "key events" (previously known as "conversions" in Universal Analytics).1
sessionKeyEventRate:event_name: For a specific key event, this is the percentage of sessions in which that key event occurred. Calculated as (Sessions with the key event / Total sessions).1
userKeyEventRate:event_name: For a specific key event, this is the percentage of users who triggered that key event. Calculated as (Users who triggered the key event / Total users).1 The distinction between session-based and user-based key event rates allows for nuanced analysis of conversion behavior.
A precise understanding of how each metric is defined and calculated is fundamental for accurate analysis. For instance, knowing that activeUsers relies on the concept of "engaged sessions" and the specific criteria for an engaged session is critical for interpreting audience data correctly.29 Similarly, understanding that itemRevenue excludes tax and shipping impacts financial reporting derived from API data.20
IV. Leveraging Custom Definitions via the API
Google Analytics 4 allows users to define custom dimensions and metrics to capture data specific to their business needs, beyond the standard set provided. The Data API fully supports reporting on these custom definitions.
A. Custom Dimensions
Custom dimensions enable the collection and analysis of non-standard textual or categorical data. They can be scoped to the User, Event, or Item level.1
1. API Syntax for User, Event, and Item Scopes
When querying custom dimensions via the API, a specific syntax is used based on their scope and the parameter name defined during their setup in the GA4 UI 1:
Event-scoped custom dimensions: customEvent:parameter_name
Example: If an event parameter article_author is collected and registered as an event-scoped custom dimension, it would be queried as customEvent:article_author.
User-scoped custom dimensions: customUser:parameter_name
Example: If a user property membership_level is collected and registered as a user-scoped custom dimension, it would be queried as customUser:membership_level.
Item-scoped custom dimensions: customItem:parameter_name
Example: If an item parameter product_color is collected within an e-commerce items array and registered as an item-scoped custom dimension, it would be queried as customItem:product_color.
For event-scoped custom dimensions that were registered before October 2020, the API syntax might require the inclusion of the event name if the parameter was registered for multiple events: customEvent:parameter_name[event_name].1 This disambiguates the parameter across different events.
2. Registering and Querying via API
Custom dimensions are not created via the API. They must first be configured within the Google Analytics 4 interface (Admin > Custom definitions).12 During this setup, the user defines a name for the dimension, selects its scope (User, Event, or Item), and specifies the existing event parameter or user property that will populate this dimension. The parameter_name used in the API request (as shown in the syntax above) must exactly match the "Event parameter name" or "User property name" provided during this UI registration.
Once registered, the properties.getMetadata API method can be used to discover all available custom dimensions for a property, including their correct API names and the customDefinition flag set to true.1 This allows applications to dynamically fetch and use custom dimensions. An API request will fail if it requests a custom dimension that has not been registered for the property.1
The API provides a standardized way to access this tailored data, but the initial setup and registration process remains anchored in the GA4 UI. The consistency between the parameter name used in data collection (e.g., in GTM or app code), the name registered in the UI, and the parameter_name in the API call is crucial for successful custom dimension reporting.
B. Custom Metrics
Custom metrics enable the analysis of numerical values from event parameters, transforming these numbers into actionable insights.12 Unlike custom dimensions which handle categorical data, custom metrics deal with quantitative data. All custom metrics in GA4 are event-scoped.1
1. API Syntax for Event-Scoped Custom Metrics
Similar to custom dimensions, custom metrics are queried using the event parameter name they are based on 1:
The base API name, which defaults to providing the sum of the custom metric, is: customEvent:parameter_name.
For custom metrics registered before October 2020, if the parameter was associated with multiple events, the event name might be required: customEvent:parameter_name[event_name].1
2. Understanding Sum, Average, and Count Variants
A significant feature of event-scoped custom metrics in the GA4 Data API is the automatic generation of three distinct metric variants for each registered custom metric. This provides analytical flexibility without requiring separate configurations for each aggregation type.1 The three variants are:
Sum (default variant):
API Name: customEvent:parameter_name
Example: If video_progress_seconds is a parameter sent with a video play event and registered as a custom metric, customEvent:video_progress_seconds would report the total sum of seconds watched across all relevant events.
Average:
API Name: averageCustomEvent:parameter_name
Example: averageCustomEvent:video_progress_seconds would report the average number of seconds watched per video play event that included this parameter.
Count:
API Name: countCustomEvent:parameter_name
Example: countCustomEvent:video_progress_seconds would report the number of video play events that included the video_progress_seconds parameter.
The properties.getMetadata API method can be used to list all available variants for a specific custom metric registered in a property.1
3. Use Cases for Each Variant
The availability of these three variants allows for a more nuanced analysis of custom numerical data 1:
Sum: This variant is typically used when the total accumulated value is of interest. Examples include the total game score achieved across all players, the total monetary value of donations collected (if 'donation_amount' is a custom metric), or the total time spent engaging with a specific interactive feature.
Average: This variant is useful for understanding the typical or central tendency of the custom metric's value per occurrence. Examples include the average score achieved per game level completed, the average donation amount per donation event, or the average time spent per use of a particular feature.
Count: This variant is used to measure the frequency of events where the custom metric parameter was present. Examples include the number of times a specific feature was used (if the custom metric is tied to a parameter logged with feature usage), the number of game levels played where a score was recorded, or the total number of donation events irrespective of the amount.
4. Registering and Querying via API
Custom metrics, like custom dimensions, must first be registered in the GA4 UI (Admin > Custom definitions > Custom metrics tab).39 This process involves providing a metric name, specifying the event parameter it is based on (this parameter must be numerical), and selecting a unit of measurement (e.g., Standard, Currency, Distance, Time). The unit of measurement provides context for interpreting the metric values in reports.39
Once registered, the Metadata API (properties.getMetadata) can be used to discover these custom metrics and their sum, average, and count variants, along with their correct API names.1 An API request will fail if it requests a custom metric that has not been registered for the property.1
The automatic generation of these three variants is a powerful and efficient aspect of the GA4 Data API. It simplifies the setup process in the UI, as only one custom metric definition is needed, yet it provides three different analytical perspectives through the API. This reduces the need for users to create multiple calculated metrics or perform post-processing to derive averages or counts from summed custom data.
Table: Custom Metric API Variants
Variant Type | API Naming Convention | Example API Name (for parameter event_value) | Description of Calculation | Typical Use Case |
Sum | customEvent:parameter_name | customEvent:event_value | Total sum of all numerical values passed for parameter_name. | Total value accumulated (e.g., total points scored, total time spent). |
Average | averageCustomEvent:parameter_name | averageCustomEvent:event_value | Average value of parameter_name per event where it occurred. | Typical value per occurrence (e.g., average points per level, average order value for a custom parameter). |
Count | countCustomEvent:parameter_name | countCustomEvent:event_value | Number of events where parameter_name was recorded. | Frequency of occurrence (e.g., number of times a feature was used, number of levels completed with a score). |
This table clarifies the naming conventions and analytical purpose of each auto-generated custom metric variant, aiding developers in selecting the appropriate variant for their reporting needs.
V. Ensuring Data Integrity: Dimension and Metric Compatibility
A fundamental aspect of working with the GA4 Data API, and indeed with GA4 reporting in general, is understanding and adhering to dimension and metric compatibility rules. Requesting incompatible combinations can lead to API errors, empty reports, or, more insidiously, reports that return data which is misleading or nonsensical.5
A. Fundamental Compatibility Rules (Scope Alignment)
The primary principle governing compatibility is scope alignment. As discussed in Section I.C, GA4 dimensions and metrics are defined at specific scopes (User, Session, Event, Item). Generally:
Dimensions and metrics of the same scope can be combined. For example, user-scoped dimensions like userAgeBracket are compatible with user-scoped metrics like totalUsers.7
Metrics from a lower or equal scope can typically be combined with dimensions of a higher scope. For instance, an event-scoped metric like eventCount can be used with a session-scoped dimension like sessionDefaultChannelGroup because events roll up into sessions.
Mixing scopes inappropriately is a primary cause of incompatibility. For example, combining a session-level dimension (e.g., sessionSource) with a user-level metric (e.g., newUsers) requires careful consideration of how GA4 attributes the user-level metric across the session dimension's values. If a new user has multiple sessions from different sources, they might be counted under each, leading to an inflated sum if one simply adds up newUsers across all sessionSource values.8
Data from different conceptual "silos" may also be incompatible if they cannot be logically joined at the requested granularity. A common example is attempting to combine advertising cost data (e.g., advertiserAdCost, which is often at a campaign or ad group level) with granular on-site interaction data (e.g., eventName, which is event-level).42 There isn't a straightforward, universally meaningful way to attribute a portion of an entire campaign's cost to each individual type of event that occurred on the site.
Some dimensions, particularly those related to traffic sources, exist at multiple scopes (e.g., firstUserDefaultChannelGroup (user scope), sessionDefaultChannelGroup (session scope), and defaultChannelGroup (event scope)). Choosing the correct scope is critical for the analysis objective.
When incompatible dimensions and metrics are requested, the GA4 system (both UI and API) may respond by graying out options in selection interfaces, returning empty reports, or issuing error messages indicating an incompatible request.17 The goal is to prevent the generation of inaccurate or uninterpretable data.
B. Utilizing the Metadata API (properties.getMetadata) for Discovery
The properties.getMetadata API method is the primary tool for programmatically discovering the dimensions and metrics available for a given GA4 property, including any custom definitions.1 As detailed in Sections II.A and III.A, the response provides rich metadata for each field, such as apiName, uiName, description, category, type (for metrics), and expression (for derived metrics).
Requesting metadata for the special property ID properties/0/metadata will return information on universal dimensions and metrics common to all properties, excluding any custom definitions specific to a particular property.14
While the Metadata API is invaluable for identifying available fields and their properties, it is important to note that the response does not explicitly detail the compatibility relationships between all possible combinations of the listed dimensions and metrics.14 It serves as a schema discovery tool, not a comprehensive compatibility matrix.
C. Verifying Combinations with properties.checkCompatibility API Method
To definitively determine if a specific set of dimensions and metrics can be validly queried together in a Core report, the GA4 Data API provides the properties.checkCompatibility method.43 This method allows developers to proactively validate a potential report structure before executing a runReport request.
The request body for checkCompatibility includes:
dimensions: An array of Dimension objects intended for the report.
metrics: An array of Metric objects intended for the report.
dimensionFilter (optional): The dimension filter expression planned for the report.
metricFilter (optional): The metric filter expression planned for the report.
compatibilityFilter (optional): An enum that can filter the response. A common usage is "COMPATIBLE" to return only those dimensions and metrics from the input that are compatible with each other, or to identify additional fields that could be compatibly added.
The response from checkCompatibility contains dimensionCompatibilities and metricCompatibilities arrays. Each element in these arrays includes the metadata for the respective dimension or metric and a compatibility enum, which can be COMPATIBLE or INCOMPATIBLE.43
This API method is a crucial tool for robust application development, as it helps prevent runtime errors and avoids the generation of misleading reports due to incompatible field combinations. It is particularly useful for applications that allow users to dynamically construct reports.
D. Using the GA4 Dimensions & Metrics Explorer Tool
For users who are not directly interacting with the API or who wish to explore compatibility manually, Google provides the GA4 Dimensions & Metrics Explorer tool.5 While some sources indicated temporary accessibility issues or lack of detailed feature descriptions in specific contexts 45, its existence and purpose as a compatibility checking tool are widely referenced.
This web-based tool typically includes a "Compatible Fields" section (or similar functionality) that allows users to select dimensions and metrics and see if they can be used together in a report.42 It serves a similar function to the checkCompatibility API method but through a user interface, making it accessible for analysts and report builders to plan their queries.
E. Common Incompatible Combinations and Why They Fail
Understanding concrete examples of incompatible combinations, particularly those arising from scope mismatches, can solidify the principles of compatibility.
Table: Examples of Incompatible Dimension-Metric Combinations
Incompatible Dimension(s) (API Name, Scope) | Incompatible Metric(s) (API Name, Scope) | Reason for Incompatibility | Potential Misinterpretation |
eventName (Event) | advertiserAdCost (N/A - Ad Platform) | Data Silo / Scope Mismatch: advertiserAdCost is aggregated at the ad campaign/group level and not directly attributable to individual on-site/app events.42 | Incorrectly attributing overall ad spend to specific user interactions, leading to flawed ROI calculations per event type. |
sessionDefaultChannelGroup (Session) | totalUsers (User) | Scope Mismatch (Conditional): If a user has multiple sessions from different channel groups, they might be counted under each, inflating the sum of totalUsers if aggregated across channel groups.5 | The sum of users across all channel groups could exceed the actual total unique users for the period, leading to an overestimation of reach per channel. |
pagePath (Event) | Any metric not totalUsers or eventCount when used in Pathing Exploration | Technique Limitation: The pathing exploration technique is designed for event/page flow and only supports user and event counts for its visualization.42 | Attempting to analyze, for example, sessions or purchaseRevenue within a pathing visualization would not be meaningful as the technique isn't built for such aggregations along a path. |
userAgeBracket (User - Demographics) | Certain custom dimensions (e.g., high-cardinality user-generated content ID) | Analytics-Imposed Restriction: Google may restrict combinations of demographic data with certain types of granular custom data for privacy or data modeling reasons.42 | The report might be empty or return an error, preventing analysis of demographic behavior related to that specific custom data. |
itemCategory (Item) | sessions (Session) | Scope Mismatch: itemCategory describes a product, relevant within e-commerce events. sessions is a higher-level aggregation. It's not directly meaningful to ask for "sessions per item category" without intervening event-level e-commerce metrics. | A report might attempt to attribute entire sessions to item categories, which is not how the data is structured. It could lead to misinterpreting session engagement based on item characteristics viewed or purchased within those sessions. |
These examples highlight that compatibility is driven by the logical relationship between data points and the level at which they are aggregated. Using the provided tools and API methods to check compatibility is a best practice for any GA4 Data API implementation.
VI. Practical Applications: Calculating Metrics and Building Reports with the API
The true value of the GA4 Data API is realized when its dimensions and metrics are combined to answer specific business questions and build insightful reports. This section delves into how common metrics are calculated and provides examples of API request structures for various analytical scenarios.
A. Deconstructing Common Metric Calculations
Many GA4 metrics are not simple counts but are derived through calculations involving other base metrics or specific event parameters. Understanding these calculations is crucial for accurate interpretation of API responses.
engagementRate: This metric is a percentage calculated as (engagedSessions / sessions) * 100.31
An engagedSession is defined as a session that meets at least one of the following criteria:
Lasted 10 seconds or longer.
Had one or more key events (conversions).
Had two or more page or screen views.29
The engagementRate is a key indicator of the quality of user interactions, moving beyond simple session counts to assess meaningful engagement.
activeUsers: This metric represents the number of unique users who had an engaged session or for whom Analytics collected specific first-time interaction events (first_visit for web, first_open for apps) along with the engagement_time_msec parameter.29
activeUsers provides a measure of the audience that is actively interacting with the site or app, rather than all users who may have had any interaction, however brief or disengaged.
averagePurchaseRevenue: This is calculated as purchaseRevenue / ecommercePurchases.1 It gives the average monetary value per e-commerce transaction.
purchaseToViewRate: This rate can be calculated in various ways depending on the context, but a common interpretation is ecommercePurchases / itemsViewed (if focusing on conversion from item views to purchases) or ecommercePurchases / screenPageViews (for a more general site-wide conversion from views).1
cartToViewRate: Similar to purchaseToViewRate, this is often addToCarts / itemsViewed or addToCarts / screenPageViews 1, indicating the propensity of users to add items to their cart after viewing them or viewing pages.
sessionKeyEventRate:EVENT_NAME: For a specified key event (e.g., sessionKeyEventRate:form_submission), this is calculated as (Sessions with the specific key event / Total sessions) * 100.1 It measures the percentage of sessions that resulted in that particular key event.
userKeyEventRate:EVENT_NAME: For a specified key event (e.g., userKeyEventRate:form_submission), this is calculated as (Users who triggered the specific key event / Total users) * 100.1 It measures the percentage of users who performed that key action at least once.
Calculated Metrics via API expression field and UI-defined Calculated Metrics:
The GA4 Data API allows for on-the-fly metric calculations by providing a mathematical expression within the Metric object of a request.16 For example, one could request averageEngagementTimePerSession with an expression like userEngagementDuration/sessions.
Furthermore, GA4 supports the creation of "Calculated Metrics" within the UI (Admin > Custom definitions > Calculated metrics tab). These user-defined formulas can combine standard and/or custom metrics (e.g., {Shipping amount} / {Purchase revenue} to create a "Shipping Revenue Percentage" metric).27 Once created and saved in the UI, these Calculated Metrics become available for querying via the Data API using their assigned API name. This allows complex, business-specific KPIs to be defined centrally and then easily retrieved programmatically.
Understanding these calculation methods allows developers and analysts to validate API data against the GA4 UI and to build more sophisticated derived metrics if needed.
B. Report Examples with Dimension-Metric Combinations (API Request Body Snippets)
The following examples illustrate common analytical scenarios and provide conceptual JSON snippets for runReport API requests. These demonstrate practical pairings of dimensions and metrics.
1. User Acquisition Analysis
Goal: Understand the sources and quality of new users.
Dimensions: date, firstUserDefaultChannelGroup.26 firstUserSourceMedium could also be used for more granularity.
Metrics: newUsers, engagedSessions (attributed to the first user's session), engagementRate, keyEvents (or conversions), averageEngagementTimePerSession.26
Example API Request Snippet:
JSON
{
"property": "properties/YOUR_GA4_PROPERTY_ID",
"dateRanges":,
"dimensions":,
"metrics":
}
This report structure, focusing on firstUser... dimensions, is critical for evaluating the effectiveness of different channels in acquiring new, engaged users.
2. Session Behavior and Quality Analysis
Goal: Analyze traffic sources for all sessions and assess their engagement levels.
Dimensions: date, sessionDefaultChannelGroup, sessionSourceMedium.2
Metrics: sessions, engagedSessions, engagementRate, averageSessionDuration, keyEvents (or sessionKeyEventRate:your_event_name).26
Example API Request Snippet:
JSON
{
"property": "properties/YOUR_GA4_PROPERTY_ID",
"dateRanges":,
"dimensions":,
"metrics":
}
Using session... scoped dimensions here allows for an understanding of channel performance on a per-session basis, which can reveal different patterns compared to first-user acquisition analysis.
3. Content Engagement and Performance
Goal: Identify which pages or screens are most popular and engaging.
Dimensions: pagePath (or unifiedPagePathScreen for combined web/app), pageTitle (or unifiedScreenName), contentGroup.3
Metrics: screenPageViews (often UI "Views"), userEngagementDuration, averageSessionDuration (can be less meaningful at page level without filtering), eventCount (for specific interaction events on pages), keyEvents.35
Example API Request Snippet:
JSON
{
"property": "properties/YOUR_GA4_PROPERTY_ID",
"dateRanges":,
"dimensions": [
{"name": "pagePath"}
],
"metrics":,
"orderBys": [{"metric": {"metricName": "screenPageViews"}, "desc": true}]
}
pagePath is often preferred over pageLocation for content aggregation as it typically excludes query parameters, providing cleaner grouping.21 userEngagementDuration per page can be a strong indicator of content value.
4. E-commerce Performance Deep Dive
Goal: Analyze product sales, revenue, and interaction with e-commerce funnels.
Dimensions: itemName, itemId, itemCategory (and its variants like itemCategory2 etc.), itemBrand, transactionId (for order-level details).20
Metrics: itemsViewed, addToCarts, itemsPurchased, itemRevenue, ecommercePurchases (transaction count), purchaseRevenue (total transaction revenue), cartToViewRate, purchaseToViewRate.20
Example API Request Snippet (Product Performance):
JSON
{
"property": "properties/YOUR_GA4_PROPERTY_ID",
"dateRanges":,
"dimensions": [
{"name": "itemName"},
{"name": "itemCategory"}
],
"metrics":,
"orderBys":
}
Effective e-commerce reporting through the API is heavily reliant on the correct implementation of GA4 e-commerce event tracking, ensuring all required parameters (like items arrays with item_id, item_name, price, quantity) are accurately sent.20
Table: Common API Report Structures
Report Goal/Type | Example Dimensions (API Names) | Example Metrics (API Names) | Key Insights Provided by this Combination |
User Acquisition | date, firstUserDefaultChannelGroup, firstUserSourceMedium | newUsers, engagedSessions, keyEvents, averageEngagementTimePerSession, firstTimePurchaserRate | Effectiveness of channels in acquiring new, high-quality users and their propensity to convert early. |
Session Quality & Traffic Source | date, sessionDefaultChannelGroup, sessionSourceMedium | sessions, engagedSessions, engagementRate, averageSessionDuration, sessionKeyEventRate:your_event_name | Performance of traffic sources on a per-session basis, identifying channels that drive engaged traffic and lead to key actions within those sessions. |
Content Performance | pagePath, pageTitle, contentGroup | screenPageViews, userEngagementDuration, averageSessionDuration (contextualized), eventCount (for specific interactions), keyEvents | Identification of popular, engaging, and high-converting content; areas for content optimization. |
E-commerce Product Analysis | itemName, itemId, itemCategory, itemBrand | itemsViewed, addToCarts, itemsPurchased, itemRevenue, cartToViewRate, purchaseToViewRate | Detailed performance of individual products or product categories, including views, add-to-cart rates, purchase rates, and revenue generation. |
E-commerce Transaction Analysis | transactionId, date, orderCoupon | ecommercePurchases, purchaseRevenue, averagePurchaseRevenue, taxAmount, shippingAmount | Order-level details, revenue trends, impact of coupons, and overall transaction metrics. |
Custom Event Analysis | eventName, customEvent:your_dim_param | eventCount, totalUsers, customEvent:your_metric_param (sum), averageCustomEvent:your_metric_param (average) | Performance and frequency of specific custom events, segmented by custom dimensions, and analysis of custom numeric parameters associated with those events. |
These examples provide templates and inspiration for constructing API queries. Developers can adapt these by substituting different dimensions and metrics based on their specific analytical objectives and the data available in their GA4 property.
VII. Conclusion: Best Practices for GA4 Data API Mastery
Effectively utilizing the Google Analytics 4 Data API requires a blend of technical proficiency in API interaction and a solid conceptual understanding of GA4's data model, particularly the roles of dimensions, metrics, scopes, and their compatibility.
Key takeaways for mastering the GA4 Data API include:
Prioritize Scope Understanding: The concept of user, session, event, and item scopes is fundamental. Always consider the scope of dimensions and metrics when constructing queries to ensure the resulting data is meaningful and accurate. Mismatched scopes are a common source of reporting errors or misinterpretations.
Leverage Metadata and Compatibility Checks: Programmatically discover available dimensions and metrics using the properties.getMetadata API method. Before executing runReport requests, especially those with dynamic or user-defined field combinations, use the properties.checkCompatibility method to validate the query structure. For manual exploration, the GA4 Dimensions & Metrics Explorer tool is an invaluable resource.
Align API Queries with Business Questions: Start with clear analytical questions. The choice of dimensions and metrics should directly support answering these questions. Avoid querying data just because it's available; focus on relevance and actionability.
Understand Metric Calculations: Many GA4 metrics are derived. Familiarize yourself with how key metrics like activeUsers, engagementRate, and various e-commerce rates are calculated to correctly interpret the data.
Utilize Custom Definitions Strategically: Custom dimensions and metrics are powerful for tailoring GA4 to specific business needs. Understand their API syntax, scope implications, and the utility of sum, average, and count variants for custom metrics.
Be Mindful of Quotas and Limits: Like any API, the GA4 Data API has usage quotas (e.g., concurrent requests, tokens per hour/day).4 Design applications to be efficient and to handle potential quota-related errors gracefully.
Stay Updated with Official Documentation: Google Analytics is an evolving platform. The API schema, available dimensions and metrics, and compatibility rules may change over time. Regularly consult the official Google Analytics Data API documentation (such as the source document indicating a "Last Updated Date" 1) for the most current information.
By adhering to these best practices, developers and analysts can harness the GA4 Data API to build robust, accurate, and insightful reporting solutions, unlocking deeper understanding from their Google Analytics 4 data. The API empowers users to move beyond standard reports, enabling customized data exploration and integration that can drive informed business decisions.
Works cited
API Dimensions & Metrics | Google Analytics | Google for Developers, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema
Create a report | Google Analytics, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/basics
GA4 API: Making Data Reports Accessible and Actionable - DiGGrowth, accessed May 15, 2025, https://diggrowth.com/blogs/google-analytics/ga4-api-making-data-reports-accessible/
Exploring the limitations of Google Analytics 4 (GA4) API - OWOX BI, accessed May 15, 2025, https://www.owox.com/blog/articles/google-analytics-api-comparison
Decoding GA4: Mastering Dimensions & Metrics Compatibility - Analytics Mates, accessed May 15, 2025, https://www.analyticsmates.com/post/understanding-ga4-dimensions-and-metrics-compatibility
Google Analytics 4 Metrics Tutorial: Everything You Need to Know Before You Transition to the New Platform | Databox, accessed May 15, 2025, https://databox.com/ga4-metrics-dimensions
GA4 Scopes explained - User, Session, Event & Item scopes - OptimizeSmart Newsletter, accessed May 15, 2025, https://www.optimizesmart.com/ga4-scopes-explained-user-session-event-item-scopes/
GA4 Scope Explained - BigQuery & Basics - Piped Out, accessed May 15, 2025, https://www.pipedout.com/resources/ga4-scope-explained
GA4 (Google Analytics 4) Dimensions Tutorial, accessed May 15, 2025, https://www.optimizesmart.com/ga4-dimensions/
GA4 Session-scoped dimensions explained - Optimize Smart, accessed May 15, 2025, https://www.optimizesmart.com/ga4-session-scoped-dimensions-explained/
GA4 Item Scoped Dimensions Explained - Optimize Smart, accessed May 15, 2025, https://www.optimizesmart.com/ga4-item-scoped-dimensions-explained/
[GA4] About custom dimensions and metrics - Analytics Help, accessed May 15, 2025, https://support.google.com/analytics/answer/14240153?hl=en
A Guide to Custom Dimensions in GA4 Setup - Netpeak Journal, accessed May 15, 2025, https://netpeak.net/blog/a-guide-to-custom-dimensions-in-ga4-setup/
Method: properties.getMetadata | Google Analytics | Google for ..., accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata
DimensionMetadata | Google Analytics, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DimensionMetadata
Method: properties.getMetadata | Google Analytics, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/getMetadata
[GA4] Analytics dimensions and metrics - Google Help, accessed May 15, 2025, https://support.google.com/analytics/table/13948007?hl=en
API Dimensions & Metrics | Google Analytics | Google for Developers, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/exploration-api-schema
User dimensions & metrics (GA4) - GA4BigQuery, accessed May 15, 2025, https://www.ga4bigquery.com/user-dimensions-metrics-ga4/
[GA4] Ecommerce purchases report - Analytics Help - Google Help, accessed May 15, 2025, https://support.google.com/analytics/answer/12924131?hl=en
Understand key GA4 dimensions and metrics - Data Community Technical Documentation, accessed May 15, 2025, https://docs.data-community.publishing.service.gov.uk/analysis/govuk-ga4/understand-ga4/
Google Analytics 4 Metrics and Dimensions | Supermetrics Documentation, accessed May 15, 2025, https://supermetrics.com/docs/integration-google-analytics4-fields
GA4 and GTM guide for Ecommerce 101 - DataTrue, accessed May 15, 2025, https://datatrue.com/en/ga4-and-gtm-guide-for-ecommerce/
MetricMetadata | Google Analytics | Google for Developers, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/MetricMetadata
Google Analytics Reporting API v4 in R Examples - 8-bit-sheep, accessed May 15, 2025, http://8-bit-sheep.com/googleAnalyticsR/articles/v4.html
Predefined Reports - Analytics - Google for Developers, accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/predefined-reports
Google Analytics 4 Calculated Metrics with Examples - Optimize Smart, accessed May 15, 2025, https://www.optimizesmart.com/calculated-metrics-in-google-analytics/
Google Analytics 4 Key Metrics and Dimensions of Your Website - OWOX BI, accessed May 15, 2025, https://www.owox.com/blog/articles/metrics-and-dimensions-in-ga
[GA4] Understand user metrics - Analytics Help - Google Help, accessed May 15, 2025, https://support.google.com/analytics/answer/12253918?hl=en
Google Analytics 4 Definitions Guide - Department of Energy, accessed May 15, 2025, https://www.energy.gov/eere/communicationstandards/google-analytics-4-definitions-guide
11 Google Analytics 4 (GA4) Metrics To Better Understand User Behavior - Measure School, accessed May 15, 2025, https://measureschool.com/ga4-metrics/
Engagement Rate Meaning | Google Analytics 4 Engagement Rate, accessed May 15, 2025, https://www.narrative.bi/metrics-index/kpis/engagement-rate
[GA4] Analytics dimensions and metrics - Analytics Help - Google Help, accessed May 15, 2025, https://support.google.com/analytics/answer/9143382
Google Analytics 4 Engagement Rate - Metric Definition - Databox, accessed May 15, 2025, https://databox.com/metric-library/metrics/google-analytics-4/engagement-rate
The Top API Metric and Dimension Combos for Google Analytics 4, accessed May 15, 2025, https://calibrate-analytics.com/insights/2023/07/24/The-Top-API-Metric-and-Dimension-Combos-for-Google-Analytics-4/
The 11 Most-Tracked Google Analytics Metrics in GA4 - Databox, accessed May 15, 2025, https://databox.com/the-most-tracked-google-analytics-metrics
Google Analytics 4 report transformation | BigQuery, accessed May 15, 2025, https://cloud.google.com/bigquery/docs/google-analytics-4-transformation
Key event rate in Google Analytics 4 explained, accessed May 15, 2025, https://www.analyticsmania.com/post/key-event-rate-in-google-analytics-4/
[GA4] Create custom metrics - Analytics Help, accessed May 15, 2025, https://support.google.com/analytics/answer/14239619?hl=en
Google Analytics 4 Custom Metrics Guide (2025) - Measure School, accessed May 15, 2025, https://measureschool.com/google-analytics-4-custom-metrics/
Custom Dimensions and Metrics in GA4, accessed May 15, 2025, https://ga4.com/custom-dimensions-and-metrics-in-google-analytics-4
[GA4] Data compatibility - Analytics Help - Google Help, accessed May 15, 2025, https://support.google.com/analytics/answer/11608978?hl=en
Method: properties.checkCompatibility | Google Analytics | Google ..., accessed May 15, 2025, https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/checkCompatibility
support.google.com, accessed May 15, 2025, https://support.google.com/analytics/answer/11608978?hl=en#:~:text=You%20can%20use%20the%20Compatible,based%20dimensions%20and%20metrics%20together.
GA4 Dimensions & Metrics Explorer - ga-dev-tools, accessed May 15, 2025, https://ga-dev-tools.google/ga4/dimensions-metrics-explorer/
accessed January 1, 1970, https://developers.google.com/analytics/devguides/ga4/dimensions-metrics-explorer
Calculated Metrics in Google Analytics 4 - InfoTrust, accessed May 15, 2025, https://infotrust.com/articles/calculated-metrics-in-google-analytics-4/
[GA4] Create calculated metrics - Analytics Help, accessed May 15, 2025, https://support.google.com/analytics/answer/14166471?hl=en
Google Analytics 4 User Acquisition Report | Rows template, accessed May 15, 2025, https://rows.com/templates/google-analytics-4-user-acquisition-report
[GA4] User acquisition report - Android - Analytics Help, accessed May 15, 2025, https://support.google.com/analytics/answer/12922540?hl=en&co=GENIE.Platform%3DAndroid
Sessions in Google Analytics Explained (GA4) - Hotjar, accessed May 15, 2025, https://www.hotjar.com/google-analytics/glossary/sessions/
How to Use Google Analytics 4 for Ecommerce Tracking in 2025 - Mailmodo, accessed May 15, 2025, https://www.mailmodo.com/guides/google-analytics-ecommerce/
Solved: Re: BigQuery & GA4 - session source / medium - Google Cloud Community, accessed May 15, 2025, https://www.googlecloudcommunity.com/gc/Data-Analytics/BigQuery-amp-GA4-session-source-medium/m-p/690582
[GA4] Engagement overview report - Analytics Help, accessed May 15, 2025, https://support.google.com/analytics/answer/13391283?hl=en
Important GA4 E-commerce Reports, accessed May 15, 2025, https://ga4.com/important-ga4-e-commerce-reports
GA4 Calculated Metrics That Improve Understanding Of Ecommerce Performance, accessed May 15, 2025, https://help.littledata.io/posts/ga4-calculated-metrics-for-ecommerce
Problems with google analytics 4 connector - Microsoft Fabric Community, accessed May 15, 2025, https://community.fabric.microsoft.com/t5/Desktop/Problems-with-google-analytics-4-connector/td-p/4647452