How To Gain Access To Google Analytics API Via Python

Posted by

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

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

  • Construct customized dashboards to display GA information.
  • Automate complex reporting jobs.
  • Integrate with other applications.

[]You can access the API reaction utilizing several various approaches, consisting of Java, PHP, and JavaScript, however this article, in specific, will focus on accessing and exporting data utilizing Python.

[]This article will just cover a few of the approaches that can be utilized to gain access to different subsets of information using different metrics and measurements.

[]I intend to compose a follow-up guide exploring various ways you can evaluate, envision, and integrate the data.

Establishing The API

Creating A Google Service Account

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

[]Once this has been created, the next step is to pick 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= "//"alt="Service Account Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been developed, navigate to the secret area and add a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a private secret. In this instance, select JSON, and then develop and

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

Contribute To Google Analytics Account

[]You will likewise want to take a copy of the e-mail that has been generated for the service account– this can be found on the primary account page.

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

Enabling The API The final and probably essential step is ensuring you have made it possible for access to the API. To do this, guarantee you are in the right project and follow this link to enable access.

[]Then, follow the actions to allow 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 triggered to complete it when 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 information. I selected Jupyter Notebooks to develop this, however you can likewise utilize other integrated designer

[]environments(IDEs)consisting of PyCharm or VSCode. Putting up Libraries The initial 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 sections 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 link! 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. Developing A Service Build The next action 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 created when creating the private secret. This

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

[]have actually saved the JSON file in the 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 want to access the information. Screenshot from author, December 2022 Completely

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

[]Then, set up the build report, calling the analytics reporting API V4, and our already defined qualifications from above.

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

Writing The Request Body

[]As soon as we have whatever established and defined, the real enjoyable begins.

[]From the API service build, there is the ability to pick the components from the action that we want to gain access to. 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.
  • At least one legitimate entry in the metrics field.

[]View ID

[]As discussed, there are a few things that are required throughout this develop stage, beginning with our viewId. As we have already specified previously, we just require to call that function name (VIEW_ID) rather than including the entire view ID once again.

[]If you wanted to collect data from a various analytics see in the future, you would simply require 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 gather the information for. This consists of a start date and an end date.

[]There are a couple of methods to write this within the construct request.

[]You can choose defined dates, for instance, 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 want to view information from the last one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

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

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

[]There are a lot of different metrics and dimensions that can be accessed. I will not go through all of them in this short article, but they can all be found together with extra details and associates here.

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

[]Both the metrics and measurements are included a dictionary format, using secret: value sets. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the value of our metric, which will have a particular format.

[]For example, if we wished to get a count of all sessions, we would add ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wished to see a count of all new users.

[]With measurements, the key will be ‘name’ followed by the colon again and the value of the measurement. For example, 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 Measurements And Metrics

[]The genuine worth is in combining metrics and dimensions 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.

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

Creating A DataFrame

[]The reaction we receive from the API is in the form of a dictionary, with all of the information in secret: value sets. To make the data much easier to view and evaluate, we can turn it into a Pandas dataframe.

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

[]Then, calling the response output, we will add the data from the measurements 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(‘information’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(worth)) []Adding The Action Data

[]When the information is 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 Demand Examples Numerous Metrics There is also the capability to integrate numerous metrics, with each set added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise request the API response just returns metrics that return specific requirements by including metric filters. It uses the following format:

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

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: pageviews’], ‘dimensions’: [], “metricFilterClauses”: [“filters”: [“metricName”: “ga: pageviews”, “operator”: “GREATER_THAN”, “comparisonValue”: “10”]]] ). execute() []Filters also work for dimensions in a similar way, but the filter expressions will be a little various due to the particular nature of dimensions.

[]For example, if you just wish to extract pageviews from users who have actually gone to the website using the Chrome browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


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

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

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

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


[]The API also lets you bucket dimensions with an integer (numerical) worth into varieties utilizing histogram buckets.

[]For instance, bucketing the sessions count dimension into 4 containers 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 offered you with a fundamental guide to accessing the Google Analytics API, composing some different requests, and gathering some meaningful insights in an easy-to-view format. I have included the build and request code, and the snippets shared to this GitHub file. I will enjoy to hear if you attempt any of these and your prepare for checking out []the data further. More resources: Included Image: BestForBest/SMM Panel