How To Access Google Analytics API Via Python

Posted by

[]The Google Analytics API offers 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 utilized to:

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

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

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

[]I hope to compose a follow-up guide exploring various methods you can evaluate, picture, and combine the data.

Setting Up The API

Producing A Google Service Account

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

[]Once this has been produced, the next step is to select the + Develop 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 Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been developed, browse to the KEYS section and include a new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a personal key. In this instance, select JSON, and then create and

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

Contribute To Google Analytics Account

[]You will likewise wish to take a copy of the email that has been produced for the service account– this can be found on the main account page.

Screenshot from Google Cloud, December 2022 The next action is to add that e-mail []as a user in Google Analytics with Analyst approvals. Screenshot from Google Analytics, December 2022

Making it possible for The API The final and perhaps essential action is guaranteeing you have actually enabled access to the API. To do this, guarantee you remain in the right project and follow this link to allow gain access to.

[]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 finish it when very first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can begin composing the []script to export the information. I chose Jupyter Notebooks to develop this, but you can also utilize other integrated designer

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

Some are special to the analytics API, and others work for future areas of the code.! pip set up– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install connect! pip install functions import connect Note: When using pip in a Jupyter note pad, include 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 customer tricks JSON download that was generated when developing the personal secret. This

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

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

[]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 = build(‘analyticsreporting’, ‘v4’, credentials=credentials)

Composing The Demand Body

[]As soon as we have whatever set up and defined, the genuine enjoyable begins.

[]From the API service build, there is the ability to pick the elements from the reaction that we want to access. This is called a ReportRequest item and needs the following as a minimum:

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

[]View ID

[]As mentioned, there are a few things that are needed throughout this develop phase, starting with our viewId. As we have currently defined previously, we just require to call that function name (VIEW_ID) instead of adding the whole view ID again.

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

[]Date Variety

[]Then we can include the date variety 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 pick defined dates, for instance, 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 wish to view information from the last 1 month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

[]The final action of the standard response 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 example, page course, traffic source, and keywords used.

[]There are a great deal of different metrics and measurements that can be accessed. I will not go through all of them in this post, however they can all be found together with extra info and associates here.

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

[]Both the metrics and measurements are added in a dictionary format, utilizing key: worth pairs. 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 wanted 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 dimensions, the secret will be ‘name’ followed by the colon again and the worth of the measurement. For example, if we wished to extract the various page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The genuine worth remains in integrating metrics and dimensions to extract the key insights we are most interested in.

[]For example, to see a count of all sessions that have actually 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= ). carry out()

Developing A DataFrame

[]The action we receive from the API remains in the type of a dictionary, with all of the data in key: worth pairs. To make the information easier to see and examine, we can turn it into a Pandas dataframe.

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

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

[]This will draw out 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, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Including The Response Data

[]Once the data remains in those lists, we can quickly 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 Response Request Examples Numerous Metrics There is likewise the ability to combine multiple metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can also ask for the API response just returns metrics that return specific criteria by including metric filters. It utilizes the following format:

if operator comparisonValue return the metric []For instance, if you just 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”: []] ). perform() []Filters likewise work for measurements in a similar way, but the filter expressions will be slightly different due to the characteristic nature of dimensions.

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

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


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

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

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

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


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

[]For example, 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 specify the varieties in histogramBuckets.

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). execute() Screenshot from author, December 2022 In Conclusion I hope this has actually supplied you with a standard guide to accessing the Google Analytics API, composing some different requests, and gathering some meaningful insights in an easy-to-view format. I have added the build and ask for code, and the snippets shared to this GitHub file. I will like to hear if you attempt any of these and your prepare for exploring []the information even more. More resources: Included Image: BestForBest/SMM Panel