GA4 APIs: Getting Started

What is Google Analytics 4?

Google describes the new Google Analytics as "privacy-first" tracking, x-channel measurement, and AI-based predictive data, all in one next-generation approach. The new Analytics can fill out data for website traffic and user behavior using Google's cutting-edge machine learning models rather than relying on "hits" from every page.

Google Analytics 4; Source: Eighty3 Creative


The "App + Web" system, on which Google Analytics 4 is built, was released in 2019 on the same platform. With the App + Web version of Analytics, marketers were given a way to track users across apps, software, and websites, primarily focusing on cross-channel data.

This indicates that its primary objective is to change how data is presented so that users—particularly the user journey from initial visit to final conversion—are the focus.

Furthermore, GA4 is all about "events." The new Google Analytics primarily presents data using these events.

Last but not least, this new Analytics' machine-learning processing enables it to close knowledge gaps caused by users who reject cookies and data collection, preventing businesses from understanding their entire customer base. When it comes to allowing Analytics to track sessions or returning users through cookies, internet users and browser manufacturers are getting increasingly picky. For instance, Mozilla Firefox has started to block Analytics, and many websites are beginning to use visitor consent to define their Analytics tracking.

New privacy protection regulations (like the GDPR and CCPA) and the declining stability of conventional analytics are the main drivers behind the need for something like Google Analytics 4. Due to the cookie consent options mandated by these laws, many businesses using the traditional Universal Google Analytics may frequently experience problems with incomplete or inaccurate data.

Understanding Google Analytics data APIs

Highlights of the new Google Analytics 4

  • It was created using modeling," which can gather from historical data and make generalizations about site traffic and user behavior. Machine learning is the primary method of data measurement. The new "Insights" feature, powered by AI, highlights data that automatically benefits marketers.
  • Giving marketers a "more thorough understanding of the customer journey across devices" is its primary goal.
  • Additionally, it is more concerned with tracking the customer journey than specific metrics across devices, pages, and market groups.
  • It is intended to be "future-proof" and operate in a world devoid of cookies or personal information.
  • The views and segments in older Universal Analytics properties have been replaced by "data streams" in Google Analytics 4.
  • The "view" level part of GA4 does not exist. GA4 only contains the Account and Property levels, unlike classic Universal Analytics, which is renowned for having three levels (Account, Property, and View).
  • Instead of requiring changed Analytics code or the gtag.js script, "event tracking" in classic Analytics is now allegedly possible within the user interface (UI). This refers to actions like page scrolling, clicking, and more.

GA4's New Capabilities

  • GA4 will let marketers amend, correct, and fine-tune the way events are tracked in their analytics without changing the on-site code.
  • Data Import can now contain various data from sources other than websites, such as apps, all in one property.
  • Within the UI, cross-domain tracking may be performed without changing any code.
  • One of the most significant advances in analytics appears to be a "Life Cycle Report" that focuses on user travel. Additionally, "templated reports for e-commerce funnels" offer marketers a way to show and visualize data; this functionality was previously exclusive to Analytics 360 accounts.

Getting Started with Google Analytics Data APIs

Installing Google Analytics 4; Source: Digital Radium


How to Install Google Analytics 4 Using Google Tag Manager

The steps for installing Google Analytics 4 and Google Tag Manager are as follows:

  1. Create a property and data stream in Google Analytics 4

If you do not intend to upgrade to Google Analytics 4 but instead want to create a new property, navigate to the Admin section of your Google Analytics interface by clicking Admin in the bottom-left corner and then selecting Create Property under the Property section.

Add your property's name next. It could be the name of your business, website, brand, etc. Select the nation where your business is based, the reporting time zone, and the primary currency used there.

Then press Next, and answer several questions. Next, you must decide on your business goals. Your interface's reports will also change depending on your selections. To make things simpler right now, select Get baseline reports.

  1. Choose Create

You need to configure your first data stream in the following action. This data source will send events to your Google Analytics 4 property. One property can contain many data sources. As an illustration, there are three websites—one for an iOS app and one for an Android app. However, even if you track many websites with a single web stream, it is usually sufficient to do so.

Add your website's URL after that (for instance, https://www.mywebsite.com). As you can see, the protocol (HTTPS) has already been chosen. Enter your website's name after that. In Google Analytics 4, you can turn Enhanced Measurement on or off when you create a web data stream. It is intended to make it easier for marketers to include as many events as possible in reports without working with developers or setting them up in Google Tag Manager.

The following events will be automatically tracked when this feature is enabled by default:

  • Page view (event name: page_view)
  • Scroll (event name: scroll)
  • Outbound link click (event name: click with the parameter outbound: true)
  • Site search (event name: view_search_results)
  • Video Engagement (events: video_start, video_progress, video_complete)
  • File Download (event name: file_download)
  • Form submissions (event names: form_start and form_submit)

You can individually turn events on and off if you would like. Toggle buttons can be accessed by clicking the gear icon in the Enhanced Measurement section.

Press the ‘Create Stream’ button when you are ready.

  1. Install Google Analytics 4 with Google Tag Manager

Inside your newly created GTM container, go to "Tags" and click on the "New" button to create a new tag. Choose "Google Analytics: GA4 Configuration" as the tag type. In the "Tag Configuration" section, enter your Measurement ID in the "Measurement ID" field. This is the ID you obtained when you created the GA4 property. Configure other settings according to your preferences. You can track Page Views, Events, Conversions, and more. Save the tag.

  1. Upload your changes to Google Tag Manager.

You should submit your GA4 changes in the GTM container and publish them once you have confirmed that the data is entered and presented correctly. You can accomplish this by clicking the SUBMIT button in the upper right corner and then carrying out the additional instructions the user interface provides. Following that, the new data should start appearing in your real-time reports as well.

  1. Real-time reports for Google Analytics
Real-time reports for google analytics; Source: Megalytics

Go to Reports > Realtime in the left sidebar of the Google Analytics 4 interface. You can see the data entering your reports here. The new report allows you to view the data at a much finer level than the previous one (Universal Analytics) did.

The first thing you will see is a map with several cards containing details on the traffic patterns, the most popular events, and the number of users over the previous 30 minutes.

Additionally, you can view a snapshot of a specific user. Clicking the View user snapshot button in the top-right corner will enable you to do that. You will then see a stream of all the events associated with that specific user, and you can click on them (just like in the DebugView) to see details up close. You can use the arrow buttons to view another user or visitor. Simply click the Exit Snapshot button in the top-right corner to end the snapshot.

Google Analytics API Examples and Implementation

Google Analytics API Example 1: Authenticating and Making a Basic API Request

Authenticating and Making a Basic API Request; Source: Swimlane


Let's dive into our first instance, which demonstrates how to authenticate your software and make a simple API request to use the Google Analytics Data API v1. This snippet fetches a file of overall occasions for a selected date range and measurement.

# Import necessary modules
from googleapiclient import discovery
from google.oauth2 import service_account
# Define an asynchronous function for the API request
async def main():
  # Authentication setup
  credentials =    service_account.Credentials.from_service_account_file('path/to/service_account.json')
  scoped_credentials =   credentials.with_scopes(['https://www.googleapis.com/auth/analytics.readonly'])
  auth = scoped_credentials.refresh(requests.Request())
  # API request configuration
  request = {
   'auth': auth,
   'body': {
     'dateRanges': [
        {
          'startDate': '7daysAgo',
          'endDate': 'today',
        },
     ],
   'dimensions': [
        {
          'name': 'eventName',
        },
   ],
   'metrics': [
        {
          'name': 'totalEvents',
        },
    ],
    'property': 'properties/your-property-id',
   },
  }
  # Make the API request
  response = await analyticsdata.runReport(request)
  print('Report data:', response['data'])
  
await main()

In this Google Analytics API example, we import the required module, define an asynchronous task for the API request, configure authentication, and configure request parameters. The resulting data provides insight into all events on a given day.

Google Analytics API Example 2: Retrieving Event Data for a Specific Event

Retrieving Event Data for a Specific Event; Source: Google Help

Our second example showcases the way to retrieve event data for a specific event from your GA4 assets. This code snippet affords a deeper understanding of consumer interactions with a selected event.

# Import necessary modules (same as Example 1)
# Define an asynchronous function for the API request
async def main():
# Authentication setup (same as Example 1)
# API request configuration
request = {
'auth': auth,
'property': 'properties/your-property-id',
'dateRanges': [
  {
    'startDate': '2023-01-01',
    'endDate': '2023-01-31',
  },
],
'dimensions': [
  {
    'name': 'eventName',
  },
],
'metrics': [
  {
    'name': 'totalEvents',
  },
],
'dimensionFilter': {
  'filter': {
     'fieldName': 'eventName',
     'stringFilter': {
        'value': 'your-event-name',
        'matchType': 'EXACT',
     },
    },
  },
}
# Make the API request
response = await analyticsdata.runReport(request)
print('Event data:', response['data'])
await main()


This instance lets you narrow your analysis to a selected event, presenting insights into consumer engagement and conduct associated with that event.

Google Analytics API Example 3: Querying Custom Metrics and GA4 API dimensions

Querying Custom Metrics and Dimensions; Source: Online metrics

Our final instance demonstrates a way to query custom metrics and GA4 API dimensions from your GA4 property, providing a greater tailor-made angle on person-to-person interactions.

# Import necessary modules (same as Example 1)
# Define an asynchronous function for the API request
async def main():
# Authentication setup (same as Example 1)
# API request configuration
request = {
'auth': auth,
'property': 'properties/your-property-id',
'dateRanges': [
  {
    'startDate': '2023-01-01',
    'endDate': '2023-01-31',
  },
],
'dimensions': [
  {
    'name': 'eventName',
  },
],
'metrics': [
  {
    'name': 'totalEvents',
  },
],
'dimensionFilter': {
  'filter': {
  'fieldName': 'eventName',
  'stringFilter': {
     'value': 'your-event-name',
     'matchType': 'EXACT',
    },
  },
},
}
# Make the API request
response = await analyticsdata.runReport(request)
print('Event data:', response['data'])
await main()

This code snippet showcases how to query custom GA4 API dimensions and metrics, allowing you to extract data tailored to your tracking needs.

Migrating from Old APIs to Google Analytics data APIs

Migrating from Old APIs to GA4 APIs; Source: Search Engine Land

Why Old APIs Won't Work with GA4

As the transition from Universal Analytics to GA4 brings approximately enormous changes in records collection, processing, and evaluation, numerous key motives make contributions to the incompatibility of the vintage APIs with GA4:

  • Data Schema Mismatch

The records schema of GA4 differs drastically from that of Universal Analytics. This discrepancy makes it more challenging for the vintage APIs, designed with the Universal Analytics schema in mind, to parse and interpret the facts successfully.

  • Event-Centric Approach

GA4's attention on occasion-based tracking is at odds with the consultation-based technique of Universal Analytics. The vintage APIs need to be equipped to handle the nuances of occasion information, central to erroneous reporting and incomplete insights.

  • Missing Out on GA4 Advancements

GA4 introduces several recent features and capabilities that enhance data analysis and offer more comprehensive insights. You omit to leverage these advancements by sticking with the antique APIs to gain an aggressive edge.

  • Future-Proofing Data Analytics

Google's strategic route is transferring in the direction of GA4, making it the recommended platform for lengthy-time period record analytics. Relying on the old APIs no longer merely limits your access to new capabilities but also places your facts analytics method at risk.

Migrating to Google Analytics data APIs

To fully harness the potential of GA4 and gain certain accurate and significant information insights, migrating from the old APIs to Google Analytics APIs is necessary. GA4 APIs are purpose-built to align with GA4's statistics model, occasion-centric method, and superior analysis functions. By making the transition, you'll benefit from:

  • Accurate Data Interpretation

GA4 APIs are designed to correctly interpret and method the event-primarily-based statistics version of GA4, providing unique and dependable insights.

  • Comprehensive Tracking

Google Analytics APIs allow you to take full advantage of GA4's advanced event monitoring competencies, allowing you to track person-to-person interactions with granularity and depth.

  • Future-Proof Analytics

By embracing GA4 APIs, you future-proof your data analytics approach, ensuring you are aligned with Google's evolving analytics environment.

Obtaining the API Secret for GA4

API Secrets for Google Analytics; Source: MonsterInsights


Step 1: Navigating to the Google Cloud Console

1. Log in to Your Google Account: Start by logging in to your Google account that is related to the GA4 property you want to get admission to. >

2. Access the Google Cloud Console: Once logged in, navigate to the Google Cloud Console at https://console.cloud.google.com/

Step 2: Creating and Configuring API Credentials

1. Select or Create a Project: If you're already associated with a challenge you intend to use on your Google Analytics APIs integration, pick it out. Otherwise, create a new project by clicking the “Select a Task"  dropdown and selecting “New Project.”

2. Enable the Analytics Data API: In the Cloud Console, navigate to the "APIs and Services" "Library" phase. Search for "Analytics Data API"; and enable it on your mission.

3. Create Credentials: After enabling the API, navigate to "APIs and Services"; and "Credentials."Click on the " + CREATE CREDENTIALS" button and choose "Service Account Key."

4. Configure a Service Account: In the "Create a Service Account" form, provide a name for your service account. You also can pick out an appropriate function, inclusive of "Project” > "Editor," to furnish the important permissions.

5. Generate the Key: Once the provider account is created, click "Create Key."; Choose the JSON key type and click on “Create."; This will download a JSON document containing your personal key.

Step three: Accessing the API Secret for Integration

1. Locate the JSON Key: Open the downloaded JSON Key report. This document incorporates the important credentials, which include the API secret, to set up a stable connection between your software and GA4.

2. Integrate the API Secret: In your application, use the API secret from the JSON key record to authenticate your requests to the GA4 API. This mystery key guarantees that your information is accessed securely and handiest by legal packages.

3. Secure Key Handling: Ensure you securely manage and keep the JSON key document. Avoid exposing this key in public repositories or insecure environments, as it offers admission to your GA4 facts.

Conclusion

GA4 APIs bring in a brand new era of record-driven selection-making. From versatile integration to more suitable reporting, those APIs empower you to get the right of entry to Google Analytics four facts. By migrating from antique APIs, you transcend obstacles, ensuring actual-time records provide insights. Obtaining the API secret now guarantees steady integration.


Embrace GA4 APIs to release unheard-of insights, spark innovation, and shape strategies for success. Your adventure with GA4 APIs begins now. Discover, experiment, and harness the power of facts to drive enterprise achievement. Elevate your alternatives with Google Analytics APIs and allow information to be the cornerstone of your triumph.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product