How To Access Google Analytics API Via Python

Posted by

[]The Google Analytics API supplies access to Google Analytics (GA) report information such as pageviews, sessions, traffic source, and bounce rate.

[]The official Google documentation explains that it can be used to:

  • Build custom-made dashboards to display GA data.
  • Automate complex reporting jobs.
  • Integrate with other applications.

[]You can access the API action utilizing numerous various techniques, including Java, PHP, and JavaScript, however this short article, in particular, will focus on accessing and exporting information using Python.

[]This article will just cover a few of the methods that can be utilized to access different subsets of data using different metrics and measurements.

[]I hope to write a follow-up guide exploring different ways you can evaluate, picture, and integrate the data.

Establishing The API

Developing A Google Service Account

[]The initial step is to produce a job or choose one within your Google Service Account.

[]Once this has actually been produced, the next step is to select the + Create Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to include some information such as a name, ID, and description.< img src= "//"alt="Service Account Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been created, browse to the secret section and add a new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a private secret. In this circumstances, choose JSON, and then develop and

wait on the file to download. Screenshot from Google Cloud, December 2022

Contribute To Google Analytics Account

[]You will also wish to take a copy of the email that has been created for the service account– this can be discovered on the main account page.

Screenshot from Google Cloud, December 2022 The next step is to add that email []as a user in Google Analytics with Expert permissions. Screenshot from Google Analytics, December 2022

Allowing The API The last and perhaps most important step is guaranteeing you have actually made it possible for access to the API. To do this, guarantee you are in the appropriate task and follow this link to enable access.

[]Then, follow the steps to enable it when promoted.

Screenshot from Google Cloud, December 2022 This is needed in order to access the API. If you miss this action, you will be triggered to finish it when first running the script. Accessing The Google Analytics API With Python Now whatever is set up in our service account, we can start composing the []script to export the information. I picked Jupyter Notebooks to produce this, however you can likewise utilize other integrated developer

[]environments(IDEs)consisting of PyCharm or VSCode. Installing Libraries The primary step is to set up the libraries that are required to run the rest of the code.

Some are special to the analytics API, and others are useful for future sections of the code.! pip install– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip set up link! pip set up functions import connect Note: When utilizing pip in a Jupyter note pad, add the!– if running in the command line or another IDE, the! isn’t required. Producing A Service Construct The next step is to set []up our scope, which is the read-only analytics API authentication link. This is followed by the client tricks JSON download that was generated when developing the private key. This

[]is used in a comparable method to an API key. To easily access this file within your code, guarantee you

[]have conserved the JSON file in the same folder as the code file. This can then easily be called with the KEY_FILE_LOCATION function.

[]Lastly, add the view ID from the analytics account with which you want to access the information. Screenshot from author, December 2022 Entirely

[]this will look like the following. We will reference these functions throughout our code.

SCOPES = [‘’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have actually included our private key file, we can add this to the credentials work by calling the file and setting it up through the ServiceAccountCredentials step.

[]Then, set up the develop report, calling the analytics reporting API V4, and our currently specified credentials from above.

qualifications = ServiceAccountCredentials.from _ json_keyfile_name(KEY_FILE_LOCATION, SCOPES) service = build(‘analyticsreporting’, ‘v4’, qualifications=qualifications)

Composing The Demand Body

[]When we have whatever established and specified, the real fun starts.

[]From the API service construct, there is the ability to select the elements from the action that we wish to gain access to. This is called a ReportRequest things and requires the following as a minimum:

  • A legitimate view ID for the viewId field.
  • At least one valid entry in the dateRanges field.
  • At least one legitimate entry in the metrics field.

[]View ID

[]As discussed, there are a few things that are required during this build stage, starting with our viewId. As we have actually already defined previously, we simply require to call that function name (VIEW_ID) rather than including the entire view ID again.

[]If you wanted to collect information from a different analytics see in the future, you would simply need to change the ID in the initial code block instead of both.

[]Date Range

[]Then we can include the date range for the dates that we want to gather the data for. This consists of a start date and an end date.

[]There are a couple of methods to write this within the develop demand.

[]You can pick specified dates, for example, between two dates, by adding the date in a year-month-date format, ‘startDate’: ‘2022-10-27’, ‘endDate’: ‘2022-11-27’.

[]Or, if you wish to view data from the last thirty days, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]The final step of the fundamental response call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session duration, and bounce rate.

[]Dimensions are the qualities of users, their sessions, and their actions. For instance, page course, traffic source, and keywords utilized.

[]There are a lot of various metrics and dimensions that can be accessed. I will not go through all of them in this post, but they can all be discovered together with additional information and associates here.

[]Anything you can access in Google Analytics you can access in the API. This includes objective conversions, begins and values, the web browser device utilized to access the website, landing page, second-page course tracking, and internal search, site speed, and audience metrics.

[]Both the metrics and measurements are added in a dictionary format, utilizing secret: worth sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and then the value of our metric, which will have a specific format.

[]For example, if we wanted to get a count of all sessions, we would include ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wished to see a count of all brand-new users.

[]With dimensions, the secret will be ‘name’ followed by the colon once again and the value of the dimension. For example, if we wanted to draw out the various page courses, it would be ‘name’: ‘ga: pagePath’.

[]Or ‘name’: ‘ga: medium’ to see the various traffic source recommendations to the site.

[]Combining Measurements And Metrics

[]The genuine worth is in combining metrics and measurements to extract the essential insights we are most interested in.

[]For example, to see a count of all sessions that have been developed from different traffic sources, we can set our metric to be ga: sessions and our dimension to be ga: medium.

reaction = service.reports(). batchGet( body= ). carry out()

Creating A DataFrame

[]The action we get from the API remains in the kind of a dictionary, with all of the information in key: worth pairs. To make the information easier to see and evaluate, we can turn it into a Pandas dataframe.

[]To turn our reaction into a dataframe, we first require to develop some empty lists, to hold the metrics and measurements.

[]Then, calling the reaction output, we will add the data from the dimensions into the empty measurements list and a count of the metrics into the metrics list.

[]This will extract the information and include it to our formerly empty lists.

dim = [] metric = [] for report in response.get(‘reports’, []: 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(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(dimension) for i, worths in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘worths’)): metric.append(int(value)) []Adding The Response Data

[]When the information is in those lists, we can quickly turn them into a dataframe by specifying the column names, in square brackets, and assigning the list worths to each column.

df = pd.DataFrame() df [” Sessions”] = metric df [” Medium”] = dim df= df [[ “Medium”,”Sessions”]] df.head()

< img src= "" alt="DataFrame Example"/ > More Response Demand Examples Numerous Metrics There is also the ability to integrate several metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering []You can likewise request the API reaction just returns metrics that return particular requirements by adding metric filters. It uses the following format:

if metricName operator return the metric []For example, if you only wanted to extract pageviews with more than 10 views.

reaction = service.reports(). batchGet( body= ‘reportRequests’: [] ). perform() []Filters likewise work for dimensions in a comparable method, however the filter expressions will be somewhat different due to the particular nature of dimensions.

[]For instance, if you just wish to extract pageviews from users who have gone to the site using the Chrome browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

reaction = service.reports(). batchGet( body= ). carry out()


[]As metrics are quantitative procedures, there is also the capability to write expressions, which work similarly to determined metrics.

[]This involves specifying an alias to represent the expression and finishing a mathematical function on 2 metrics.

[]For example, you can determine completions per user by dividing the variety of conclusions by the variety of users.

action = service.reports(). batchGet( body= ). perform()


[]The API likewise lets you pail dimensions with an integer (numeric) worth into ranges using pie chart containers.

[]For instance, bucketing the sessions count measurement into 4 buckets of 1-9, 10-99, 100-199, and 200-399, you can use the HISTOGRAM_BUCKET order type and define the ranges in histogramBuckets.

response = service.reports(). batchGet( body= ). execute() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a standard guide to accessing the Google Analytics API, writing some different requests, and gathering some significant insights in an easy-to-view format. I have actually added the construct and ask for code, and the bits shared to this GitHub file. I will like to hear if you try any of these and your prepare for exploring []the data even more. More resources: Included Image: BestForBest/SMM Panel