The Google Analytics API offers access to Google Analytics (GA) report data such as pageviews, sessions, traffic source, and bounce rate.
The official Google paperwork discusses that it can be utilized to:
- Construct customized dashboards to show GA data.
- Automate complex reporting jobs.
- Integrate with other applications.
This post will just cover a few of the approaches that can be used to access various subsets of information utilizing different metrics and measurements.
I want to write a follow-up guide checking out different ways you can evaluate, picture, and combine the information.
Setting Up The API
Producing A Google Service Account
The first step is to produce a project or select one within your Google Service Account.
When this has actually been created, 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= "// 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 developed, browse to the secret section and add a brand-new key. Screenshot from Google Cloud, December 2022  This will trigger you to produce and download a private key. In this circumstances, choose JSON, and after that develop and
await the file to download. Screenshot from Google Cloud, December 2022
Add To Google Analytics Account
You will also want to take a copy of the e-mail that has been produced 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 Analyst permissions. Screenshot from Google Analytics, December 2022
Making it possible for The API The last and arguably most important step is ensuring you have actually enabled access to the API. To do this, ensure you remain in the correct job 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 very first running the script. Accessing The Google Analytics API With Python Now everything is established in our service account, we can begin writing the script to export the information. I chose Jupyter Notebooks to produce this, however you can likewise utilize other incorporated designer
environments(IDEs)consisting of PyCharm or VSCode. Putting up Libraries The initial 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 areas of the code.! pip set up– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip install connect! pip set up functions import link Note: When utilizing pip in a Jupyter note pad, include the!– if running in the command line or another IDE, the! isn’t required. Creating 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 generated when developing the personal key. This
is utilized in a similar way to an API key. To quickly access this file within your code, guarantee you
have actually saved the JSON file in the very same folder as the code file. This can then easily be called with the KEY_FILE_LOCATION function.
Finally, add the view ID from the analytics account with which you wish to access the data. Screenshot from author, December 2022 Altogether
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 actually included our private crucial file, we can include this to the credentials function 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 currently defined qualifications from above.
credentials = ServiceAccountCredentials.from _ json_keyfile_name(KEY_FILE_LOCATION, SCOPES) service = build(‘analyticsreporting’, ‘v4’, qualifications=qualifications)
Writing The Demand Body
As soon as we have whatever set up and defined, the genuine enjoyable begins.
From the API service build, there is the ability to select the aspects from the reaction that we wish to access. This is called a ReportRequest object 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 valid entry in the metrics field.
As mentioned, there are a couple of things that are required during this develop stage, starting with our viewId. As we have currently specified previously, we just require to call that function name (VIEW_ID) rather than adding the entire view ID once again.
If you wished to gather data from a various analytics see in the future, you would just require to change the ID in the initial code block rather than both.
Then we can add the date variety for the dates that we wish to collect the information for. This consists of a start date and an end date.
There are a number of ways to compose this within the construct demand.
You can pick 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 thirty days, you can set the start date as ’30daysAgo’ and the end date as ‘today.’
Metrics And Dimensions
The final action of the standard reaction 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 attributes of users, their sessions, and their actions. For example, page course, traffic source, and keywords used.
There are a lot of different metrics and measurements that can be accessed. I will not go through all of them in this article, however they can all be found together with additional info and attributes here.
Anything you can access in Google Analytics you can access in the API. This includes goal conversions, begins and values, the browser gadget utilized to access the site, landing page, second-page path tracking, and internal search, website speed, and audience metrics.
Both the metrics and dimensions are included a dictionary format, using key: worth pairs. For metrics, the key 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 wished 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 key will be ‘name’ followed by the colon again and the worth of the dimension. For example, if we wished to extract the different page paths, it would be ‘name’: ‘ga: pagePath’.
Or ‘name’: ‘ga: medium’ to see the different traffic source recommendations to the site.
Combining Dimensions And Metrics
The genuine worth remains in integrating metrics and measurements to extract the key insights we are most thinking about.
For instance, to see a count of all sessions that have been developed from various traffic sources, we can set our metric to be ga: sessions and our dimension to be ga: medium.
reaction = service.reports(). batchGet( body= ‘reportRequests’:  ). execute()
Creating A DataFrame
The response we obtain from the API is in the kind of a dictionary, with all of the data in secret: value sets. To make the data simpler to see and evaluate, we can turn it into a Pandas dataframe.
To turn our response into a dataframe, we first require to create some empty lists, to hold the metrics and dimensions.
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 draw out the data and add it to our previously 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: measurements = row.get(‘dimensions’,  dateRangeValues = row.get(‘metrics’,  for header, dimension in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘worths’)): metric.append(int(value)) Adding The Action Data
As soon as the information remains in those lists, we can easily 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= "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 Numerous Metrics There is likewise the capability to combine several metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [, ] Filtering You can likewise ask for the API action just returns metrics that return particular criteria by including metric filters. It uses the following format:
if metricName return the metric For instance, if you only wanted to draw out pageviews with more than ten views.
action = service.reports(). batchGet( body= ). perform() Filters likewise work for measurements in a comparable way, however the filter expressions will be a little various due to the particular nature of dimensions.
For instance, if you only want to draw out pageviews from users who have visited the site using the Chrome browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.
action = service.reports(). batchGet( body= ‘reportRequests’:  ). execute()
As metrics are quantitative procedures, there is likewise the ability to write expressions, which work similarly to calculated metrics.
This includes specifying an alias to represent the expression and finishing a mathematical function on two metrics.
For instance, you can compute conclusions per user by dividing the number of conclusions by the variety of users.
action = service.reports(). batchGet( body= ‘reportRequests’:  ). carry out()
The API likewise lets you bucket dimensions with an integer (numerical) value into ranges utilizing histogram pails.
For example, bucketing the sessions count measurement into four pails of 1-9, 10-99, 100-199, and 200-399, you can utilize the HISTOGRAM_BUCKET order type and define the ranges in histogramBuckets.
response = service.reports(). batchGet( body= ‘reportRequests’:  ). perform() 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 demands, and gathering some significant insights in an easy-to-view format. I have actually added the construct and request code, and the snippets shared to this GitHub file. I will love to hear if you try any of these and your prepare for checking out the information further. More resources: Featured Image: BestForBest/Best SMM Panel