September 21, 2021

Python Tutorial 20: Google Analytics API Access Using Python to Integrate GA Data 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.

python tutorial

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.

Python Tutorial – Enable Google Analytics 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.

python tutorial

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 analytic 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.

Python Tutorial – 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.

python tutorial

cope = ['https://www.googleapis.com/auth/analytics.readonly']
api_key = 'yourjsonfilelocationpath.json'
credentials = service_account.Credentials.from_service_account_file(api_key,scopes=scope)
service = build('analytics', 'v4', credentials=credentials, discoveryServiceUrl=('https://analyticsreporting.googleapis.com/$discovery/rest?version=v4'))

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 creating a custom dashboard

Python Tutorial – Extract the data you need and Upload 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 like 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 get a 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 gspread.

element_information = {
“Page": A,
"Sales": B
}

df = pd.DataFrame(element_information)
value_list = sh.values_update('your sheet name!A1', params={'valueInputOption': 'USER_ENTERED'},body=dict(values=df.T.reset_index().T.values.tolist()))

Full Python Script of Google Analytics API 4

If you would like to have the full version of the Python Script of Amazon Product Price Tracker, please subscribe to our newsletter by adding the message Python Tutorial 20. We would send you the script immediately to your mailbox.

Contact us

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

  • Support my 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 to 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 code on Buyfromlo products and digital software
  • Subscribe to our monthly membership through Patreon to enjoy exclusive benefits (www.patreon.com/louisludigital)

Leave a Reply

Your email address will not be published. Required fields are marked *