Chapter 20: Google Analytics 4 API Access Using Python to Integrate with your Custom Marketing Dashboard

Business dashboard is a must-have thing nowadays if you are running an online business. Connecting with different platforms and consolidating diverse data into one place, does help you understand a better picture. Of course, making a more proper and better decision can’t happen without an organized and up-to-date date in the dashboard.

Web analytics platforms are indispensable for any corporation nowadays, and Google Analytics is the most popular one. Previously I shared how to extract the Google search console SEO data to your Google Sheets Dashboard. You can tell that that set of data lacks many other dimensions and metrics. In Particular, you are running an eCommerce store, and conversion data is critical to you.

In this Python Tutorial, I would walk you through how to connect Google Analytics API using Python and extract the data you need. By the end of this piece, you can learn what dimensions and metrics you call via API in the Python Script. Also, you can integrate this automated update with your Google Sheets Dashboard. You can have more full gear and dimensional insight.

Table of Contents: Google Analytics 4 API Integration Using Python

Most Popular Google Analytics 4 Fundamental and Advanced Couresa Tutorial

  1. Google analytics 4 fundamental
  2. Google analytics 4 advanced

Enable Google Analytics 4 API

First thing first, we need to enable the Google Analytics API in the APIs developer. Just search google analytics in the library and you can find the GA V4 version API. This is the most advanced programmatic method and you can use it to build up a custom dashboard

Then as well as other Google API scripts, you need to create a credential and key with downloading the JSON file. In fact, you can continue to use the Google search console project credential and key you created in the previous chapter.

What’s more, you login into your Google Analytics account and add the API robot email to the view access management in the admin section. So the robot can get access to your GA.

Set up Google Analytics Scope and Credential in the Python Script

If we read the GA data, the Google Analytics API scope is the URL attached below. And it also requires us to add the discovery service URL in the build method

https://www.googleapis.com/auth/analytics.readonly

service = build('analytics', 'v4', credentials=credentials, discoveryServiceUrl=('https://analyticsreporting.googleapis.com/$discovery/rest?version=v4'))

It is a JSON format, like the Shopify product data feed. Basically, this is the GA open data framework we can extract. Last but not least, creating the API key variable and credentials is as well as other Google APIs scripts.

Use report() and batchGet() to framework the data scope

Google Analytics API has two top-level methods. One is the search and the other is the batchGet. Within the method, we can tell GA which accounts we are going to access, and what data dimensions we want. And in the data scope block, basically, you need to have these values.

response = service.reports().batchGet(
body={
'reportRequests':[
{
'viewId': 'xxxxxxxxx',
'dateRanges': [{'startDate': '2021-06-01','endDate': '2021-06-30'}],
'metrics': [{'expression': 'ga:goalCompletionsAll'}],
'dimensions': [{"name": "ga:landingPagePath"}],
'orderBys': [{"fieldName": "ga:goalCompletionsAll", "sortOrder": "DESCENDING"}],
'pageSize': 20
}]
}
).execute()

  • viewId: This is your GA account and the specific property view ID. Please don’t mix up with the tracking ID. The location of the view ID should be here like the screencap attached.
  • dateRanges: You can set the start date and end date of your data. This section is just like the date range you select in GA
  • Metrics and Dimensions: Metric is defined as what specific data you are extracting, such as sessions, transactions, time on site, etc. Dimension is defined as what macro perspective you are looking into, such as country level, device, pages, etc. For more details of value you can use in the documentation, you can refer to the UA Dimensions & Metrics Explorer
  • orderBys: This is the descending or ascending order setting. Basically, we use it to rank the metrics data we set above
  • pageSize: You don’t need to fetch all data every time and you can set up the number based on your needs by creating a custom dashboard

Extract the data you need and Upload it to Google Sheets

When commanding B by the above python codings, it’s working with GA APIs if the data result you aim to fetch comes up in this format. The next step would be creating a loop to extract the value without this format

First of all, we create two variables without values, A and B. They would be used in a moment. You can tell that all the data is sitting within reports. So we can use the get() method in a loop to extract the data block we need first. That would be the columnheader, dimensions, metricHeader, and rows within the reports.

for report in response.get('reports', []):

columnSection = report.get('columnHeader', {})
dimensionSection = columnSection.get('dimensions', [])
metricSection = columnSection.get('metricHeader', {}).get('metricHeaderEntries', [])
rows = report.get('data', {}).get('rows', [])

Secondly, within the rows, there are dimensions and metrics. You can find that the value in this block respectively is the target we’re going to extract. So we need to create a loop called row here. It’s working if you print and the data comes up like the screencap attached.

for row in rows:

dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])

You can tell that the fetched data at the moment is not ready to upload yet. We need to further extract the core values we need from this loop.

1) Remove the header “ga:” and combine two variables to function using zip() method

Python’s zip() method creates an iterator that will aggregate elements from two or more iterables. You can use the resulting iterator to quickly and consistently solve common programming problems. Here you can see dimensionSection and dimensions are two variables in the same path to get the final value. So for this loop called dimension we can use zip() method to run together.

for header, dimension in zip(dimensionSection, dimensions):
A.append(dimension)

2) Extract the metric value

When dealing with iterators, we also need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in the form of an enumerating object.

for i, values in enumerate(dateRangeValues):
for metaicHeader, value in zip(metricHeaders, values.get('values')):
B.append(int(value))

3) Frame the data using Pandas and Upload it to Google Sheets using Easy2Digital API.

Full Python Script of Google Analytics 4 API

If you would like to have the full version of the Python Script of Google Analytics 4 API, please subscribe to our newsletter by adding the message “Chapter 20”. We would send you the script immediately to your mailbox.

Contact us

I hope you enjoy reading Chapter 20: Google Analytics 4 API Access Using Python to Integrate with your Custom Marketing Dashboard. If you did, please support us by doing one of the things listed below, because it always helps out our channel.

  • Support and donate to our channel through PayPal (paypal.me/Easy2digital)
  • Subscribe to my channel and turn on the notification bell Easy2Digital Youtube channel.
  • Follow and like my page Easy2Digital Facebook page
  • Share the article on your social network with the hashtag #easy2digital
  • Buy products with Easy2Digital 10% OFF Discount code (Easy2DigitalNewBuyers2021)
  • You sign up for our weekly newsletter to receive Easy2Digital latest articles, videos, and discount codes
  • Subscribe to our monthly membership through Patreon to enjoy exclusive benefits (www.patreon.com/louisludigital)

FAQ:

Q1: What is the Google Analytics 4 API?

A: The Google Analytics 4 API is an interface that allows developers to interact with Google Analytics 4 data programmatically.

Q2: What can I do with the Google Analytics 4 API?

A: With the Google Analytics 4 API, you can retrieve data from your Google Analytics 4 properties, create custom reports, automate data extraction, and integrate Google Analytics data with other applications.

Q3: How do I access the Google Analytics 4 API?

A: To access the Google Analytics 4 API, you need to create a project in the Google Cloud Console, enable the Analytics API, set up authentication, and obtain an API key or access token.

Q4: What programming languages can I use with the Google Analytics 4 API?

A: You can use any programming language that supports HTTP requests and JSON, such as Python, Java, JavaScript, PHP, Ruby, or .NET.

Q5: What data can I retrieve with the Google Analytics 4 API?

A: The Google Analytics 4 API allows you to retrieve a wide range of data, including user engagement metrics, event data, conversion data, user properties, and audience insights.

Q6: Can I use the Google Analytics 4 API for real-time data?

A: Yes, the Google Analytics 4 API provides real-time data retrieval capabilities, allowing you to access up-to-the-minute information about user interactions on your website or app.

Q7: Are there any limitations or quotas for using the Google Analytics 4 API?

A: Yes, there are certain limitations and quotas imposed by Google on the usage of the Google Analytics 4 API. These include limits on the number of requests per day, the amount of data retrieved per request, and the number of concurrent requests.

Q8: Can I modify data using the Google Analytics 4 API?

A: No, the Google Analytics 4 API is read-only and does not allow modification of data. If you need to make changes to your Google Analytics configuration or send data to your property, you should use the Google Analytics administration interface or measurement protocol.

Q9: Is the Google Analytics 4 API free to use?

A: Yes, the Google Analytics 4 API is free to use. However, keep in mind that there may be associated costs if you exceed the free quota limits or if you use additional Google Cloud services in conjunction with the API.

Q10: Where can I find documentation and resources for the Google Analytics 4 API?

A: You can find official documentation, code samples, and other resources for the Google Analytics 4 API on the Google Developers website.

Google API Endpoint Recommendation

Google Shopping Product Scraper API

Price: US$18

Google Shopping SERP scraper crawls the product information from Google Shopping channel. API allows to filter by platform country domain, user location, language. Users can scrape the product information using a keyword query. The scraped dataset include product name, pricing, shipping fees, brand name, product page URL etc.

More API options from the Google collection. 

SAVE UP TO 50% and EXPLORE MORE!