How To Access Google Analytics API Via Python

Posted by

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

[]The main Google paperwork describes that it can be used to:

  • Build customized dashboards to show GA data.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

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

[]This short article will simply cover a few of the methods that can be used to access various subsets of information utilizing various metrics and measurements.

[]I wish to write a follow-up guide checking out different ways you can examine, envision, and integrate the information.

Setting Up The API

Developing A Google Service Account

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

[]Once this has actually been produced, the next action is to pick the + Create 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 Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been produced, navigate to the secret section and include a brand-new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a private key. In this instance, choose JSON, and after that 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 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 authorizations. Screenshot from Google Analytics, December 2022

Enabling The API The final and probably crucial action is ensuring you have actually enabled access to the API. To do this, ensure you remain in the correct 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 needed in order to access the API. If you miss this step, you will be prompted to finish it when 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 picked Jupyter Notebooks to create this, but you can also utilize other incorporated developer

[]environments(IDEs)consisting of PyCharm or VSCode. Installing Libraries The first step is to set up the libraries that are needed 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 connect! pip install functions import connect Note: When using pip in a Jupyter note pad, add the!– if running in the command line or another IDE, the! isn’t needed. 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 client tricks JSON download that was generated when creating the private secret. This

[]is used in a similar method to an API key. To easily access this file within your code, ensure you

[]have saved the JSON file in the 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 want 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 included our personal essential file, we can add this to the qualifications work by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, established the build report, calling the analytics reporting API V4, and our already defined credentials from above.

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

Composing The Demand Body

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

[]From the API service build, there is the capability to select the aspects from the response that we wish to gain access to. This is called a ReportRequest things and needs the following as a minimum:

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

[]View ID

[]As pointed out, there are a couple of things that are required during this construct stage, beginning with our viewId. As we have currently specified previously, we just need to call that function name (VIEW_ID) rather than including the whole view ID again.

[]If you wished to collect data from a various analytics see in the future, you would just need to change the ID in the initial code block instead of both.

[]Date Variety

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

[]There are a couple of ways to compose this within the construct request.

[]You can choose specified dates, for example, in 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 one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

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

[]Measurements are the qualities of users, their sessions, and their actions. For instance, page course, traffic source, and keywords used.

[]There are a lot of various metrics and dimensions that can be accessed. I won’t go through all of them in this article, however they can all be discovered together with extra info and attributes here.

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

[]Both the metrics and dimensions are added in a dictionary format, using key: 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 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 wanted to see a count of all new users.

[]With dimensions, the key will be ‘name’ followed by the colon again and the worth of the dimension. For example, if we wanted to draw out the different page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Measurements And Metrics

[]The real value is in combining metrics and measurements to draw out the essential insights we are most interested in.

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

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

Producing A DataFrame

[]The response we get from the API is in the kind of a dictionary, with all of the data in secret: worth pairs. To make the information much easier to see and evaluate, we can turn it into a Pandas dataframe.

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

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

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

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

if return the metric []For instance, if you just wished to draw out pageviews with more than 10 views.

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [], ‘measurements’: [‘name’: ‘ga: pagePath’], “metricFilterClauses”: [“filters”: [“metricName”: “ga: pageviews”, “operator”: “GREATER_THAN”, “comparisonValue”: “10”]]] ). carry out() []Filters also work for measurements in a similar method, but the filter expressions will be slightly various due to the characteristic nature of dimensions.

[]For instance, if you only want to extract pageviews from users who have checked out the website utilizing the Chrome web browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


[]As metrics are quantitative measures, there is also the ability to compose expressions, which work similarly to calculated metrics.

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

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

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


[]The API also lets you pail measurements with an integer (numerical) worth into ranges utilizing pie chart buckets.

[]For example, bucketing the sessions count dimension into four buckets 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= ). execute() 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 collecting some significant insights in an easy-to-view format. I have included the build and request code, and the bits shared to this GitHub file. I will enjoy to hear if you try any of these and your plans for checking out []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel