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 utilized to:

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

[]You can access the API action utilizing a number of different approaches, including Java, PHP, and JavaScript, however this post, in specific, will concentrate on accessing and exporting information utilizing Python.

[]This short article will just cover some of the techniques that can be used to gain access to various subsets of information using various metrics and measurements.

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

Setting Up The API

Developing A Google Service Account

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

[]As soon as this has actually been created, the next action is to select the + Develop Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to add some information such as a name, ID, and description.< img src= "//"alt="Service Account Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been created, navigate to the KEYS section and add a brand-new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a personal key. In this instance, select JSON, and then produce and

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

Contribute To Google Analytics Account

[]You will also want 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 action is to add that email []as a user in Google Analytics with Expert approvals. Screenshot from Google Analytics, December 2022

Making it possible for The API The last and arguably crucial action is guaranteeing you have allowed access to the API. To do this, ensure you remain in the proper job and follow this link to make it possible for gain access to.

[]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 prompted 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 start writing the []script to export the data. I chose Jupyter Notebooks to develop this, but you can likewise utilize other incorporated developer

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

Some are distinct to the analytics API, and others are useful for future sections of the code.! pip install– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip set up functions import link Note: When using pip in a Jupyter notebook, add the!– if running in the command line or another IDE, the! isn’t required. Producing A Service Construct The next action 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 generated when creating the personal secret. This

[]is utilized in a similar way to an API secret. To easily access this file within your code, ensure you

[]have conserved the JSON file in the very 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 information. Screenshot from author, December 2022 Altogether

[]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 included our private essential file, we can include this to the credentials operate 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.

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

Writing The Demand Body

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

[]From the API service build, there is the ability to pick the aspects from the response that we want to access. This is called a ReportRequest things and requires the following as a minimum:

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

[]View ID

[]As discussed, there are a couple of things that are required throughout this construct phase, beginning with our viewId. As we have actually already defined formerly, we just 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 see in the future, you would simply require to alter the ID in the preliminary code block instead of both.

[]Date Variety

[]Then we can include the date variety for the dates that we want 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 select specified dates, for example, in between two 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 data from the last one month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Measurements

[]The last action of the standard action call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session duration, and bounce rate.

[]Measurements are the attributes of users, their sessions, and their actions. For instance, page path, traffic source, and keywords utilized.

[]There are a lot of different metrics and dimensions that can be accessed. I won’t go through all of them in this article, but they can all be found together with additional info and associates here.

[]Anything you can access in Google Analytics you can access in the API. This includes goal conversions, starts and values, the web 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: 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 instance, if we wanted to get a count of all sessions, we would add ‘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 measurement. For instance, 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 Dimensions And Metrics

[]The real value is in integrating metrics and measurements to extract the essential insights we are most thinking about.

[]For example, 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 measurement to be ga: medium.

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

Developing A DataFrame

[]The reaction we obtain from the API remains in the type of a dictionary, with all of the information in secret: worth sets. To make the information simpler to see and analyze, we can turn it into a Pandas dataframe.

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

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

[]This will extract 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: dimensions = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, values in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Adding The Response Data

[]As soon as the information is in those lists, we can easily turn them into a dataframe by specifying the column names, in square brackets, and appointing 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 Reaction Demand Examples Several Metrics There is also the ability to integrate several metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise ask for the API reaction only returns metrics that return specific requirements by adding metric filters. It uses the following format:

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

response = service.reports(). batchGet( body= ). carry out() []Filters likewise work for measurements in a similar method, but the filter expressions will be slightly different due to the characteristic nature of dimensions.

[]For example, if you just wish to draw out pageviews from users who have checked out the site utilizing the Chrome internet browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

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


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

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

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

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). perform()


[]The API likewise lets you bucket measurements with an integer (numerical) worth into varieties using histogram pails.

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

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