The Google Analytics API supplies access to Google Analytics (GA) report data such as pageviews, sessions, traffic source, and bounce rate.
The official Google documents explains that it can be used to:
- Develop customized control panels to display GA data.
- Automate complex reporting tasks.
- Incorporate with other applications.
This article will simply cover some of the techniques that can be used to access different subsets of data utilizing various metrics and measurements.
I hope to write a follow-up guide checking out various ways you can analyze, picture, and combine the information.
Establishing The API
Creating A Google Service Account
The primary step is to create a task or select one within your Google Service Account.
Once this has been created, the next step is to select the + Develop 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= "// www.w3.org/2000/svg%22%20viewBox=%220%200%201152%201124%22%3E%3C/svg%3E"alt="Service Account Details"width="1152"height=" 1124"data-src="https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-12-at-20.20.21-639b81474320f-sej.png"/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been created, navigate to the KEYS section and include a new secret. Screenshot from Google Cloud, December 2022  This will prompt you to produce and download a private secret. In this instance, select JSON, and then create and
wait on the file to download. Screenshot from Google Cloud, December 2022
Add To Google Analytics Account
You will likewise wish to take a copy of the email that has actually been generated for the service account– this can be discovered on the primary account page.
Screenshot from Google Cloud, December 2022 The next step is to include that e-mail as a user in Google Analytics with Expert permissions. Screenshot from Google Analytics, December 2022
Enabling The API The last and perhaps crucial step is ensuring you have actually enabled access to the API. To do this, guarantee you remain in the correct project and follow this link to make it possible for access.
Then, follow the actions to enable it when promoted.
Screenshot from Google Cloud, December 2022 This is needed in order to access the API. If you miss this step, you will be triggered to complete it when very first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can begin writing the script to export the data. I selected Jupyter Notebooks to create this, however you can likewise use other integrated designer
environments(IDEs)consisting of PyCharm or VSCode. Putting up Libraries The primary step is to install the libraries that are required to run the remainder of the code.
Some are special to the analytics API, and others work for future areas of the code.! pip install– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip install functions import connect Note: When utilizing pip in a Jupyter note pad, include the!– if running in the command line or another IDE, the! isn’t needed. Developing 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 customer tricks JSON download that was produced when developing the private key. This
is utilized in a comparable method to an API key. To easily access this file within your code, ensure 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, include the view ID from the analytics account with which you want to access the information. Screenshot from author, December 2022 Completely
this will look like the following. We will reference these functions throughout our code.
SCOPES = [‘ https://www.googleapis.com/auth/analytics.readonly’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ Once we have added our personal crucial file, we can include this to the credentials work by calling the file and setting it up through the ServiceAccountCredentials action.
Then, set up the develop report, calling the analytics reporting API V4, and our currently specified credentials from above.
credentials = ServiceAccountCredentials.from _ json_keyfile_name(KEY_FILE_LOCATION, SCOPES) service = develop(‘analyticsreporting’, ‘v4’, credentials=qualifications)
Composing The Request Body
As soon as we have everything set up and specified, the genuine enjoyable begins.
From the API service build, there is the capability to pick the components 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 legitimate entry in the dateRanges field.
- A minimum of one legitimate entry in the metrics field.
As mentioned, there are a couple of things that are needed during this develop phase, starting with our viewId. As we have actually already defined formerly, we simply require to call that function name (VIEW_ID) rather than adding the whole view ID once again.
If you wished to gather information from a different analytics view in the future, you would simply require to change the ID in the initial code block instead of both.
Then we can add the date variety for the dates that we want to gather the data for. This includes a start date and an end date.
There are a number of methods to compose this within the construct demand.
You can select defined dates, for instance, between 2 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 data from the last 1 month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’
Metrics And Measurements
The last step of the basic action call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session period, and bounce rate.
Dimensions are the characteristics of users, their sessions, and their actions. For instance, page course, traffic source, and keywords used.
There are a great deal of various metrics and dimensions that can be accessed. I won’t go through all of them in this post, but they can all be discovered together with additional information and attributes here.
Anything you can access in Google Analytics you can access in the API. This consists of objective conversions, begins and values, the internet browser gadget utilized to access the website, landing page, second-page path tracking, and internal search, website speed, and audience metrics.
Both the metrics and measurements are included a dictionary format, using key: value pairs. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and after that 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 new users.
With dimensions, the key will be ‘name’ followed by the colon once again and the value of the measurement. For instance, if we wished to extract the various page courses, it would be ‘name’: ‘ga: pagePath’.
Or ‘name’: ‘ga: medium’ to see the various traffic source referrals to the site.
Integrating Dimensions And Metrics
The genuine worth remains in combining metrics and measurements to draw out the essential insights we are most thinking about.
For example, to see a count of all sessions that have been produced from different traffic sources, we can set our metric to be ga: sessions and our dimension to be ga: medium.
response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: sessions’], ‘measurements’: ] ). perform()
Producing A DataFrame
The reaction we receive from the API is in the form of a dictionary, with all of the information in secret: value pairs. To make the data easier to see and evaluate, we can turn it into a Pandas dataframe.
To turn our action into a dataframe, we first require to develop some empty lists, to hold the metrics and dimensions.
Then, calling the action output, we will append the data from the dimensions into the empty measurements list and a count of the metrics into the metrics list.
This will extract the data 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(‘data’, ). get(‘rows’,  for row in rows: dimensions = row.get(‘measurements’,  dateRangeValues = row.get(‘metrics’,  for header, dimension in zip(dimensionHeaders, dimensions): dim.append(dimension) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘worths’)): metric.append(int(worth)) Adding The Reaction Data
Once the information remains in those lists, we can quickly turn them into a dataframe by specifying the column names, in square brackets, and assigning the list values to each column.
df = pd.DataFrame() df [” Sessions”] = metric df [” Medium”] = dim df= df [[ “Medium”,”Sessions”]] df.head()
< img src= "https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-13-at-20.30.15-639b817e87a2c-sej.png" alt="DataFrame Example"/ > More Reaction Request Examples Several Metrics There is likewise the capability to combine multiple metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering You can likewise ask for the API reaction only returns metrics that return certain requirements by including metric filters. It utilizes the following format:
if metricName operator comparisonValue return the metric For instance, if you only wanted to draw out pageviews with more than ten views.
response = service.reports(). batchGet( body= ‘reportRequests’:  ). carry out() Filters also work for dimensions in a similar method, but the filter expressions will be slightly different due to the characteristic nature of measurements.
For instance, if you just want to draw out pageviews from users who have actually visited the site utilizing the Chrome web browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.
reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: , ‘metrics’: [‘expression’: ‘ga: pageviews’], “measurements”: [“name”: “ga: web browser”], “dimensionFilterClauses”: ] ). perform()
As metrics are quantitative procedures, there is likewise the ability to write expressions, which work likewise to computed metrics.
This includes specifying an alias to represent the expression and finishing a mathematical function on 2 metrics.
For instance, you can determine conclusions per user by dividing the variety of completions by the number of users.
action = service.reports(). batchGet( body= ). carry out()
The API also lets you container measurements with an integer (numeric) value 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= ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a standard guide to accessing the Google Analytics API, composing some different demands, and collecting some meaningful insights in an easy-to-view format. I have included the construct and request code, and the bits shared to this GitHub file. I will love to hear if you attempt any of these and your prepare for exploring the information even more. More resources: Featured Image: BestForBest/Best SMM Panel