How To Access 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 discusses that it can be used to:

  • Construct custom-made dashboards to display GA information.
  • Automate complex reporting tasks.
  • Incorporate with other applications.

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

[]This article will just cover a few of the approaches that can be used to access different subsets of data using different metrics and dimensions.

[]I intend to write a follow-up guide checking out different methods you can evaluate, visualize, and combine the information.

Establishing The API

Producing A Google Service Account

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

[]Once this has been created, the next action is to choose the + Produce 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 created, browse to the secret area and add a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a personal key. In this circumstances, choose JSON, and after that create 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 actually been created for the service account– this can be discovered 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

Making it possible for The API The final and arguably essential step is ensuring you have allowed access to the API. To do this, guarantee you remain in the right task and follow this link to allow gain access to.

[]Then, follow the steps 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 complete it when first running the script. Accessing The Google Analytics API With Python Now everything is established in our service account, we can begin composing the []script to export the information. I picked Jupyter Notebooks to produce this, but you can likewise utilize other integrated designer

[]environments(IDEs)consisting of PyCharm or VSCode. Installing Libraries The primary step is to set up the libraries that are required to run the rest of the code.

Some are distinct to the analytics API, and others work for future areas of the code.! pip install– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip set up link! pip set up 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 required. Producing 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 secrets JSON download that was generated when developing the personal key. This

[]is used in a similar method to an API secret. To quickly access this file within your code, guarantee 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, include the view ID from the analytics account with which you would like to access the data. Screenshot from author, December 2022 Entirely

[]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 added our private essential file, we can add this to the qualifications operate by calling the file and setting it up through the ServiceAccountCredentials step.

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

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

Writing The Demand Body

[]As soon as we have whatever established and specified, the real fun starts.

[]From the API service develop, there is the capability to select the elements from the action that we wish to access. This is called a ReportRequest object and needs 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 pointed out, there are a couple of things that are required throughout this construct phase, beginning with our viewId. As we have actually already specified previously, we just need to call that function name (VIEW_ID) instead of including the entire view ID once again.

[]If you wished to collect data from a different analytics see in the future, you would just need to change the ID in the preliminary code block rather than both.

[]Date Variety

[]Then we can add the date variety for the dates that we want to collect the information for. This includes a start date and an end date.

[]There are a number of methods to compose this within the construct request.

[]You can choose specified dates, for instance, between two dates, by adding 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 1 month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Measurements

[]The last step of the standard 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.

[]Dimensions are the characteristics of users, their sessions, and their actions. For instance, page course, traffic source, and keywords utilized.

[]There are a great deal of different metrics and measurements 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 attributes here.

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

[]Both the metrics and measurements are added in a dictionary format, using key: worth sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a particular 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 brand-new users.

[]With measurements, the key will be ‘name’ followed by the colon once again and the worth of the measurement. 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 referrals to the website.

[]Combining Measurements And Metrics

[]The genuine worth is in combining metrics and measurements to extract the essential insights we are most thinking about.

[]For instance, to see a count of all sessions that have been created 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= ‘reportRequests’: [] ). execute()

Developing A DataFrame

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

[]To turn our response into a dataframe, we initially need to produce some empty lists, to hold the metrics and measurements.

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

[]As soon as the information remains in those lists, we can quickly 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 Response Demand Examples Multiple Metrics There is also the capability to integrate several metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering []You can also request the API reaction only returns metrics that return particular requirements by adding metric filters. It utilizes the following format:

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

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

[]For instance, if you just want to draw out pageviews from users who have actually visited the site using the Chrome web browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


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

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

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

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


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

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

response = service.reports(). batchGet( body= ). execute() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a fundamental guide to accessing the Google Analytics API, writing some various requests, and collecting some significant insights in an easy-to-view format. I have included the develop and ask for code, and the bits shared to this GitHub file. I will enjoy to hear if you try any of these and your prepare for checking out []the data further. More resources: Featured Image: BestForBest/Best SMM Panel