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 official Google paperwork describes that it can be utilized to:

  • Build custom-made dashboards to show GA data.
  • Automate complex reporting jobs.
  • Integrate with other applications.

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

[]This article will simply cover a few of the methods that can be utilized to access various subsets of data using various metrics and measurements.

[]I want to write a follow-up guide exploring different methods you can examine, imagine, and combine the information.

Setting Up The API

Creating A Google Service Account

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

[]As soon as this has actually been developed, the next action is to choose the + Produce 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 Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been produced, browse to the KEYS area and include a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a personal key. In this instance, select JSON, and after that create and

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

Add To Google Analytics Account

[]You will also wish to take a copy of the e-mail that has actually been generated for the service account– this can be discovered on the main account page.

Screenshot from Google Cloud, December 2022 The next step is to include that email []as a user in Google Analytics with Analyst permissions. Screenshot from Google Analytics, December 2022

Allowing The API The last and perhaps essential action is guaranteeing you have enabled access to the API. To do this, ensure you are in the proper task and follow this link to make it possible for gain access to.

[]Then, follow the steps to enable it when promoted.

Screenshot from Google Cloud, December 2022 This is required in order to access the API. If you miss this action, you will be prompted to complete 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 selected Jupyter Notebooks to produce this, but you can also utilize other incorporated developer

[]environments(IDEs)including PyCharm or VSCode. Setting up Libraries The primary 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 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 connect Note: When utilizing pip in a Jupyter notebook, add the!– if running in the command line or another IDE, the! isn’t required. Creating A Service Develop The next action is to set []up our scope, which is the read-only analytics API authentication link. This is followed by the customer secrets JSON download that was created when creating the personal key. This

[]is utilized in a comparable method to an API key. To quickly access this file within your code, guarantee 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, include the view ID from the analytics account with which you would like 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 actually included our private essential file, we can include this to the credentials work by calling the file and setting it up through the ServiceAccountCredentials step.

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

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

Composing The Request Body

[]Once we have everything set up and defined, the genuine enjoyable starts.

[]From the API service develop, there is the capability to choose the elements from the response that we want to gain access to. This is called a ReportRequest item and requires the following as a minimum:

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

[]View ID

[]As discussed, there are a few things that are required during this develop phase, beginning with our viewId. As we have actually already specified previously, we just need to call that function name (VIEW_ID) rather than adding the whole view ID again.

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

[]Date Range

[]Then we can include the date range for the dates that we want to collect the data for. This consists of 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 example, 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 information 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 fundamental reaction 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 course, traffic source, and keywords used.

[]There are a great deal of different metrics and dimensions that can be accessed. I will not go through all of them in this post, but 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 goal conversions, starts and values, the web browser gadget utilized to access the website, landing page, second-page course tracking, and internal search, website speed, and audience metrics.

[]Both the metrics and measurements are included a dictionary format, using key: value sets. 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 instance, 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 measurements, the key will be ‘name’ followed by the colon once again and the worth of the measurement. For instance, if we wanted to draw out the different page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Dimensions And Metrics

[]The real value 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 been produced from different traffic sources, we can set our metric to be ga: sessions and our measurement to be ga: medium.

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

Developing A DataFrame

[]The response we obtain from the API is in the kind of a dictionary, with all of the data in key: value sets. To make the information much easier to view and analyze, we can turn it into a Pandas dataframe.

[]To turn our action into a dataframe, we initially need to produce 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 measurements list and a count of the metrics into the metrics list.

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

[]Once the data remains in those lists, we can easily turn them into a dataframe by specifying the column names, in square brackets, and designating the list values 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 Request Examples Numerous Metrics There is likewise the ability 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 only returns metrics that return certain requirements by including metric filters. It uses the following format:

if operator comparisonValue return the metric []For instance, if you only wanted to draw out pageviews with more than ten views.

reaction = service.reports(). batchGet( body= ). carry out() []Filters likewise work for measurements in a comparable method, but 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 actually visited the website utilizing the Chrome browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


[]As metrics are quantitative steps, there is likewise the ability to write expressions, which work likewise to determined metrics.

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

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

response = service.reports(). batchGet( body= ). carry out()


[]The API also lets you container measurements with an integer (numerical) worth into varieties utilizing histogram containers.

[]For instance, bucketing the sessions count dimension into 4 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.

reaction = service.reports(). batchGet( body= ). perform() Screenshot from author, December 2022 In Conclusion I hope this has provided 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 actually included the build and ask for code, and the snippets shared to this GitHub file. I will like to hear if you try any of these and your prepare for checking out []the information further. More resources: Featured Image: BestForBest/SMM Panel