How To Entry Google Analytics API Through Python

The Google Analytics API supplies entry to Google Analytics (GA) report information resembling pageviews, classes, visitors supply, and bounce charge.

The official Google documentation explains that it may be used to:

  • Construct customized dashboards to show GA information.
  • Automate complicated reporting duties.
  • Combine with different functions.

You’ll be able to entry the API response utilizing a number of completely different strategies, together with Java, PHP, and JavaScript, however this text, particularly, will deal with accessing and exporting information utilizing Python.

This text will simply cowl among the strategies that can be utilized to entry completely different subsets of information utilizing completely different metrics and dimensions.

I hope to put in writing a follow-up information exploring alternative ways you’ll be able to analyze, visualize, and mix the info.

Setting Up The API

Creating A Google Service Account

Step one is to create a undertaking or choose one inside your Google Service Account.

As soon as this has been created, the following step is to pick the + Create Service Account button.

Screenshot from Google Cloud, December 2022

You’ll then be promoted so as to add some particulars resembling a reputation, ID, and outline.

Service Account DetailsScreenshot from Google Cloud, December 2022

As soon as the service account has been created, navigate to the KEYS part and add a brand new key.

Service Account KeyScreenshot from Google Cloud, December 2022

This can immediate you to create and obtain a personal key. On this occasion, choose JSON, after which create and watch for the file to obtain.

JSON Credentials KeyScreenshot from Google Cloud, December 2022

Add To Google Analytics Account

Additionally, you will need to take a replica of the e-mail that has been generated for the service account – this may be discovered on the principle account web page.

Google Account EmailScreenshot from Google Cloud, December 2022

The following step is so as to add that e mail as a person in Google Analytics with Analyst permissions.

Email in Google AnalyticsScreenshot from Google Analytics, December 2022

Enabling The API

The ultimate and arguably most necessary step is guaranteeing you’ve enabled entry to the API. To do that, guarantee you’re within the right undertaking and comply with this hyperlink to allow entry.

Then, comply with the steps to allow it when promoted.

Enabling the APIScreenshot from Google Cloud, December 2022

That is wanted with a view to entry the API. When you miss this step, you may be prompted to finish it when first working the script.

Accessing The Google Analytics API With Python

Now the whole lot is about up in our service account, we are able to begin writing the script to export the info.

I selected Jupyter Notebooks to create this, however you too can use different built-in developer environments (IDEs) together with PyCharm or VSCode.

Putting in Libraries

Step one is to put in the libraries which can be wanted to run the remainder of the code.

Some are distinctive to the analytics API, and others are helpful for future sections of the code.

!pip set up --upgrade google-api-python-client
!pip3 set up --upgrade oauth2client
from apiclient.discovery import construct
from oauth2client.service_account import ServiceAccountCredentials
!pip set up join
!pip set up capabilities
import join

Be aware: When utilizing pip in a Jupyter pocket book, add the ! – if working within the command line or one other IDE, the ! isn’t wanted.

Creating A Service Construct

The following step is to arrange our scope, which is the read-only analytics API authentication hyperlink.

That is adopted by the shopper secrets and techniques JSON obtain that was generated when creating the personal key. That is utilized in an analogous approach to an API key.

To simply entry this file inside your code, guarantee you’ve saved the JSON file in the identical folder because the code file. This could then simply be known as with the KEY_FILE_LOCATION perform.

Lastly, add the view ID from the analytics account with which you want to entry the info.

Google Analytics View IDScreenshot from writer, December 2022

Altogether it will seem like the next. We’ll reference these capabilities all through our code.

SCOPES = ['']
KEY_FILE_LOCATION = 'client_secrets.json'

As soon as now we have added our personal key file, we are able to add this to the credentials perform by calling the file and setting it up by means of the ServiceAccountCredentials step.

Then, arrange the construct report, calling the analytics reporting API V4, and our already outlined credentials from above.

credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
service = construct('analyticsreporting', 'v4', credentials=credentials)

Writing The Request Physique

As soon as now we have the whole lot arrange and outlined, the actual enjoyable begins.

From the API service construct, there’s the power to pick the weather from the response that we need to entry. That is known as a ReportRequest object and requires the next at least:

  • A sound view ID for the viewId area.
  • No less than one legitimate entry within the dateRanges area.
  • No less than one legitimate entry within the metrics area.

View ID

As talked about, there are some things which can be wanted throughout this construct stage, beginning with our viewId. As now we have already outlined beforehand, we simply have to name that perform identify (VIEW_ID) moderately than including the entire view ID once more.

When you wished to gather information from a distinct analytics view sooner or later, you’d simply want to alter the ID within the preliminary code block moderately than each.

Date Vary

Then we are able to add the date vary for the dates that we need to gather the info for. This consists of a begin date and an finish date.

There are a few methods to put in writing this throughout the construct request.

You’ll be able to choose outlined dates, for instance, between two dates, by including the date in a year-month-date format, ‘startDate’: ‘2022-10-27’, ‘endDate’: ‘2022-11-27’.

Or, if you wish to view information from the final 30 days, you’ll be able to set the beginning date as ‘30daysAgo’ and the tip date as ‘immediately.’

Metrics And Dimensions

The ultimate step of the fundamental response name is setting the metrics and dimensions. Metrics are the quantitative measurements from Google Analytics, resembling session depend, session length, and bounce charge.

Dimensions are the traits of customers, their classes, and their actions. For instance, web page path, visitors supply, and key phrases used.

There are numerous completely different metrics and dimensions that may be accessed. I received’t undergo all of them on this article, however they’ll all be discovered along with further data and attributes right here.

Something you’ll be able to entry in Google Analytics you’ll be able to entry within the API. This contains objective conversions, begins and values, the browser system used to entry the web site, touchdown web page, second-page path monitoring, and inside search, website velocity, and viewers metrics.

Each the metrics and dimensions are added in a dictionary format, utilizing key:worth pairs. For metrics, the important thing can be ‘expression’ adopted by the colon (:) after which the worth of our metric, which could have a selected format.

For instance, if we wished to get a depend of all classes, we might add ‘expression’: ‘ga:classes’. Or ‘expression’: ‘ga:newUsers’ if we wished to see a depend of all new customers.

With dimensions, the important thing can be ‘identify’ adopted by the colon once more and the worth of the dimension. For instance, if we wished to extract the completely different web page paths, it could be ‘identify’: ‘ga:pagePath’.

Or ‘identify’: ‘ga:medium’ to see the completely different visitors supply referrals to the positioning.

Combining Dimensions And Metrics

The actual worth is in combining metrics and dimensions to extract the important thing insights we’re most fascinated with.

For instance, to see a depend of all classes which were created from completely different visitors sources, we are able to set our metric to be ga:classes and our dimension to be ga:medium.

response = service.stories().batchGet(
        'reportRequests': [
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:medium'}]

Creating A DataFrame

The response we get from the API is within the type of a dictionary, with all the information in key:worth pairs. To make the info simpler to view and analyze, we are able to flip it right into a Pandas dataframe.

To show our response right into a dataframe, we first have to create some empty lists, to carry the metrics and dimensions.

Then, calling the response output, we’ll append the info from the scale into the empty dimensions checklist and a depend of the metrics into the metrics checklist.

This can extract the info and add it to our beforehand empty lists.

dim = []
metric = []

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

columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
rows = report.get('information', {}).get('rows', [])

for row in rows:

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

for header, dimension in zip(dimensionHeaders, dimensions):

for i, values in enumerate(dateRangeValues):
for metricHeader, worth in zip(metricHeaders, values.get('values')):

Including The Response Knowledge

As soon as the info is in these lists, we are able to simply flip them right into a dataframe by defining the column names, in sq. brackets, and assigning the checklist values to every column.

df = pd.DataFrame()
df["Sessions"]= metric
df["Medium"]= dim
df= df[["Medium","Sessions"]]

DataFrame Example 

Extra Response Request Examples

A number of Metrics

There may be additionally the power to mix a number of metrics, with every pair added in curly brackets and separated by a comma.

'metrics': [
              {"expression": "ga:pageviews"},
              {"expression": "ga:sessions"}


It’s also possible to request the API response solely returns metrics that return sure standards by including metric filters. It makes use of the next format:

if {metricName} {operator} {comparisonValue}
   return the metric

For instance, should you solely wished to extract pageviews with greater than ten views.

response = service.stories().batchGet(
        'reportRequests': [
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:pageviews'}],
          'dimensions': [{'name': 'ga:pagePath'}],

"metricFilterClauses": [{
"filters": [{
"metricName": "ga:pageviews",
"operator": "GREATER_THAN",
"comparisonValue": "10"

Filters additionally work for dimensions in an analogous approach, however the filter expressions can be barely completely different because of the attribute nature of dimensions.

For instance, should you solely need to extract pageviews from customers who’ve visited the positioning utilizing the Chrome browser, you’ll be able to set an EXTRACT operator and use ‘Chrome’ because the expression.

response = service.stories().batchGet(
        'reportRequests': [
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:pageviews'}],
          "dimensions": [{"name": "ga:browser"}],
          "dimensionFilterClauses": [
          "filters": [
              "dimensionName": "ga:browser",
              "operator": "EXACT",
              "expressions": ["Chrome"]


As metrics are quantitative measures, there’s additionally the power to put in writing expressions, which work equally to calculated metrics.

This includes defining an alias to signify the expression and finishing a mathematical perform on two metrics.

For instance, you’ll be able to calculate completions per person by dividing the variety of completions by the variety of customers.

response = service.stories().batchGet(
        'reportRequests': [
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
          "expression": "ga:goal1completions/ga:users",
          "alias": "completions per user"


The API additionally permits you to bucket dimensions with an integer (numeric) worth into ranges utilizing histogram buckets.

For instance, bucketing the classes depend dimension into 4 buckets of 1-9, 10-99, 100-199, and 200-399, you should use the HISTOGRAM_BUCKET order kind and outline the ranges in histogramBuckets.

response = service.stories().batchGet(
        'reportRequests': [
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
          "metrics": [{"expression": "ga:sessions"}],
          "dimensions": [
              "name": "ga:sessionCount",
              "histogramBuckets": ["1","10","100","200","400"]
         "orderBys": [
              "fieldName": "ga:sessionCount",
              "orderType": "HISTOGRAM_BUCKET"
Histogram Example Screenshot from writer, December 2022

In Conclusion

I hope this has supplied you with a primary information to accessing the Google Analytics API, writing some completely different requests, and accumulating some significant insights in an easy-to-view format.

I’ve added the construct and request code, and the snippets shared to this GitHub file.

I’ll love to listen to should you attempt any of those and your plans for exploring the info additional.

Extra assets:

Featured Picture: BestForBest/Shutterstock

Leave a Reply

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

Schedule Call

👋🏻 Hi friend, how are you today?

Need help? contact us here... 👇