How To Gain Access To Google Analytics API Via Python

Posted by

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

[]The main Google documents discusses that it can be used to:

  • Develop custom control panels to display GA information.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

[]You can access the API action utilizing several different techniques, consisting of Java, PHP, and JavaScript, however this article, in particular, will focus on accessing and exporting information utilizing Python.

[]This article will just cover a few of the approaches that can be utilized to access various subsets of data utilizing various metrics and measurements.

[]I wish to write a follow-up guide exploring various methods you can evaluate, imagine, and integrate the information.

Setting Up The API

Creating A Google Service Account

[]The first step is to develop a job or select one within your Google Service Account.

[]Once this has been developed, 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 details 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 been created, browse to the secret section and include a new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a personal secret. In this circumstances, choose JSON, and then produce and

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

Add To Google Analytics Account

[]You will likewise want to take a copy of the email that has been generated for the service account– this can be found on the primary account page.

Screenshot from Google Cloud, December 2022 The next action is to include that email []as a user in Google Analytics with Analyst consents. Screenshot from Google Analytics, December 2022

Allowing The API The last and arguably crucial action is guaranteeing you have made it possible for access to the API. To do this, ensure you remain in the appropriate task and follow this link to allow access.

[]Then, follow the actions to allow it when promoted.

Screenshot from Google Cloud, December 2022 This is required in order to access the API. If you miss this action, you will be prompted to finish it when very first running the script. Accessing The Google Analytics API With Python Now everything is set up in our service account, we can begin writing the []script to export the data. I picked Jupyter Notebooks to create this, however you can also use other incorporated designer

[]environments(IDEs)including PyCharm or VSCode. Setting up Libraries The first step is to install the libraries that are required to run the rest of the code.

Some are unique to the analytics API, and others are useful for future sections of the code.! pip set up– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import build from oauth2client.service _ account import ServiceAccountCredentials! pip set up link! pip install functions import connect Note: When using pip in a Jupyter note pad, include 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 secrets JSON download that was created when producing the private key. This

[]is used in a similar way to an API key. To quickly access this file within your code, guarantee you

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

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

[]this will appear 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 action.

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

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

Composing The Request Body

[]When we have everything set up and defined, the genuine fun begins.

[]From the API service construct, there is the capability to pick the elements from the response that we wish to gain access to. This is called a ReportRequest object and needs the following as a minimum:

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

[]View ID

[]As mentioned, there are a couple of things that are needed throughout this construct stage, beginning with our viewId. As we have currently specified formerly, we just need to call that function name (VIEW_ID) instead of including the entire view ID once again.

[]If you wished to gather data from a different analytics view in the future, you would just require to change the ID in the initial code block instead of both.

[]Date Variety

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

[]There are a number of ways to write this within the construct request.

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

[]Or, if you want to view information from the last 1 month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The final step of the standard 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 characteristics of users, their sessions, and their actions. For instance, page path, traffic source, and keywords used.

[]There are a great deal of various metrics and measurements that can be accessed. I will not go through all of them in this post, however they can all be found together with additional information and associates here.

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

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

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

[]With measurements, the key will be ‘name’ followed by the colon again and the value of the dimension. For example, if we wished to extract the various page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The genuine worth is in integrating metrics and dimensions to extract the essential insights we are most thinking about.

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

response = service.reports(). batchGet( body= ). execute()

Creating A DataFrame

[]The response we get from the API remains in the form of a dictionary, with all of the data in secret: value pairs. To make the data simpler to view and analyze, we can turn it into a Pandas dataframe.

[]To turn our action into a dataframe, we initially need to produce some empty lists, to hold the metrics and measurements.

[]Then, calling the response output, we will append the information from the dimensions into the empty measurements list and a count of the metrics into the metrics list.

[]This will draw out the data and add it to our formerly empty lists.

dim = [] metric = [] for report in response.get(‘reports’, []: columnHeader = report.get(‘columnHeader’, ) dimensionHeaders = columnHeader.get(‘measurements’, [] metricHeaders = columnHeader.get(‘metricHeader’, ). get(‘metricHeaderEntries’, [] rows = report.get(‘information’, ). get(‘rows’, [] for row in rows: measurements = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(measurement) for i, values in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘worths’)): metric.append(int(value)) []Adding The Action Data

[]Once the information is in those lists, we can easily turn them into a dataframe by defining the column names, in square brackets, and designating the list values to each column.

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

< img src= "" alt="DataFrame Example"/ > More Action Demand Examples Several Metrics There is likewise the capability to combine multiple metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can also ask for the API reaction just returns metrics that return particular criteria by including metric filters. It utilizes the following format:

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

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() []Filters likewise work for dimensions in a comparable way, but the filter expressions will be slightly various due to the characteristic nature of dimensions.

[]For example, if you only wish to draw out pageviews from users who have actually visited the website using the Chrome browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

reaction = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out()


[]As metrics are quantitative procedures, there is also the ability to compose expressions, which work likewise to determined metrics.

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

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [“expression”: “ga: goal1completions]] ). perform()


[]The API also lets you pail dimensions with an integer (numerical) worth into varieties utilizing pie chart pails.

[]For example, bucketing the sessions count dimension into 4 containers of 1-9, 10-99, 100-199, and 200-399, you can utilize the HISTOGRAM_BUCKET order type and define the ranges in histogramBuckets.

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has provided you with a fundamental guide to accessing the Google Analytics API, composing some different requests, and gathering some significant insights in an easy-to-view format. I have added the build and ask for code, and the snippets shared to this GitHub file. I will like to hear if you try any of these and your prepare for checking out []the information even more. More resources: Featured Image: BestForBest/Best SMM Panel