How To Gain Access To Google Analytics API Via Python

Posted by

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

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

  • Build custom dashboards to display GA information.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

[]You can access the API action using numerous different techniques, including Java, PHP, and JavaScript, however this article, in specific, will concentrate on accessing and exporting information using Python.

[]This post will just cover some of the methods that can be used to gain access to various subsets of information utilizing various metrics and measurements.

[]I hope to write a follow-up guide exploring various ways you can examine, visualize, and combine the data.

Establishing The API

Creating A Google Service Account

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

[]Once this has actually been developed, the next action is to choose the + Develop Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to add 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 actually been developed, navigate to the KEYS section and add a new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a private key. In this circumstances, select JSON, and after that develop and

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

Contribute To Google Analytics Account

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

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

Enabling The API The last and perhaps most important step is guaranteeing you have actually allowed access to the API. To do this, guarantee you are in the proper job and follow this link to allow 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 action, you will be triggered to finish it when very first running the script. Accessing The Google Analytics API With Python Now whatever is set up in our service account, we can begin composing the []script to export the data. I selected Jupyter Notebooks to produce this, but you can also use other integrated designer

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

Some are distinct to the analytics API, and others work for future sections of the code.! pip install– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip set up functions import connect Note: When using pip in a Jupyter notebook, add 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 client tricks JSON download that was produced when producing the personal secret. This

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

[]have conserved the JSON file in the exact 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 wish to access the data. Screenshot from author, December 2022 Completely

[]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 added our private key file, we can include this to the credentials work by calling the file and setting it up through the ServiceAccountCredentials step.

[]Then, set up the construct 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’, credentials=credentials)

Composing The Request Body

[]When we have whatever set up and defined, the real enjoyable starts.

[]From the API service construct, there is the ability to choose the components from the reaction that we wish to access. This is called a ReportRequest object and needs the following as a minimum:

  • A valid view ID for the viewId field.
  • At least one valid 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 phase, starting with our viewId. As we have actually currently specified previously, we simply need to call that function name (VIEW_ID) rather than including the whole view ID once again.

[]If you wanted to gather information from a various analytics view in the future, you would simply need to alter the ID in the preliminary code block rather than both.

[]Date Variety

[]Then we can include the date range for the dates that we wish to collect the information for. This includes a start date and an end date.

[]There are a number of ways to compose this within the build demand.

[]You can pick 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 want to see information from the last 1 month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]The final step of the fundamental reaction call is setting the metrics and dimensions. 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 example, page course, traffic source, and keywords utilized.

[]There are a great deal of different metrics and dimensions that can be accessed. I won’t go through all of them in this post, however they can all be found together with extra info and attributes here.

[]Anything you can access in Google Analytics you can access in the API. This includes goal conversions, starts and values, the browser gadget used to access the website, 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 secret: value sets. 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 instance, if we wanted to get a count of all sessions, we would include ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wanted 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 dimension. For instance, if we wished to extract the different page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Measurements And Metrics

[]The real worth remains in integrating metrics and measurements to extract the key insights we are most thinking about.

[]For example, to see a count of all sessions that have actually been produced 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’: [] ). carry out()

Creating A DataFrame

[]The reaction we obtain from the API remains in the form of a dictionary, with all of the information in key: worth sets. 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 first need to produce 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 include 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: dimensions = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, dimensions): dim.append(dimension) for i, values in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘values’)): metric.append(int(worth)) []Adding The Action Data

[]When the data remains in those lists, we can quickly turn them into a dataframe by defining 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 Action Request Examples Numerous Metrics There is also the capability to integrate numerous metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can likewise ask for the API response just returns metrics that return particular requirements by adding metric filters. It utilizes the following format:

if metricName comparisonValue return the metric []For example, if you just wanted to draw out pageviews with more than ten views.

response = service.reports(). batchGet( body= ). execute() []Filters also work for dimensions in a similar way, but the filter expressions will be a little different due to the characteristic nature of dimensions.

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

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


[]As metrics are quantitative steps, there is likewise the capability to compose expressions, which work likewise to computed metrics.

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

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

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], “metrics”: [ga: users”, “alias”: “conclusions per user”]] ). execute()


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

[]For instance, bucketing the sessions count dimension into four pails of 1-9, 10-99, 100-199, and 200-399, you can use the HISTOGRAM_BUCKET order type and specify the ranges in histogramBuckets.

action = service.reports(). batchGet( body= ). perform() Screenshot from author, December 2022 In Conclusion I hope this has actually offered you with a basic guide to accessing the Google Analytics API, writing some different demands, and collecting some meaningful insights in an easy-to-view format. I have actually added the develop and request code, and the snippets shared to this GitHub file. I will love to hear if you attempt any of these and your plans for exploring []the information further. More resources: Included Image: BestForBest/Best SMM Panel