How To Access Google Analytics API Via Python

Posted by

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

[]The main Google documentation explains that it can be utilized to:

  • Develop custom control panels to display GA data.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API action utilizing numerous different approaches, including Java, PHP, and JavaScript, however this article, in particular, will concentrate on accessing and exporting data using Python.

[]This short article will just cover some of the methods that can be utilized to gain access to various subsets of data utilizing different metrics and dimensions.

[]I want to compose a follow-up guide exploring different ways you can examine, visualize, and combine the data.

Setting Up The API

Creating A Google Service Account

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

[]As soon as this has been produced, the next step is to pick the + Produce Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to include 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 actually been created, navigate to the KEYS area and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a personal secret. In this instance, choose JSON, and after that develop and

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

Contribute To Google Analytics Account

[]You will also want to take a copy of the email that has been generated for the service account– this can be discovered on the main account page.

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

Allowing The API The final and probably most important step is guaranteeing you have actually allowed access to the API. To do this, ensure you remain in the correct task and follow this link to make it possible for access.

[]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 step, you will be triggered to finish it when very first running the script. Accessing The Google Analytics API With Python Now whatever is set up in our service account, we can start composing the []script to export the data. I chose Jupyter Notebooks to develop this, however you can also utilize other incorporated developer

[]environments(IDEs)consisting of PyCharm or VSCode. Putting up 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 work for future sections of the code.! pip set up– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import build from oauth2client.service _ account import ServiceAccountCredentials! pip set up connect! 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 needed. Developing 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 produced when producing the private key. This

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

[]have actually conserved the JSON file in the exact 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 wish to access the data. 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 included our private essential file, we can include this to the qualifications work 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 currently defined credentials from above.

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

Composing The Demand Body

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

[]From the API service develop, there is the capability to pick the components from the reaction 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.
  • At least one legitimate entry in the dateRanges field.
  • A minimum of one valid entry in the metrics field.

[]View ID

[]As discussed, there are a couple of things that are required throughout this develop stage, starting with our viewId. As we have currently defined formerly, we simply need to call that function name (VIEW_ID) rather than including the entire view ID once again.

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

[]There are a number of methods to write this within the develop request.

[]You can select specified dates, for example, 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 see information from the last 30 days, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]The last action of the basic reaction call is setting the metrics and dimensions. 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 path, traffic source, and keywords utilized.

[]There are a great deal of different metrics and dimensions that can be accessed. I won’t go through all of them in this post, but they can all be discovered together with extra information 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 gadget used to access the website, landing page, second-page path tracking, and internal search, website speed, and audience metrics.

[]Both the metrics and dimensions 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 new users.

[]With dimensions, the key will be ‘name’ followed by the colon again and the worth of the measurement. For example, if we wished 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 real value remains in integrating metrics and measurements to draw out the crucial insights we are most thinking about.

[]For instance, 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.

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

Producing A DataFrame

[]The response we receive from the API is in the form of a dictionary, with all of the data in secret: value sets. To make the data much easier to see and evaluate, 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 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 extract the data and include it to our formerly 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(‘dimensions’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, values in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(worth)) []Adding The Action Data

[]When 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 Action Request Examples Numerous Metrics There is likewise the ability to combine multiple metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise request the API reaction only returns metrics that return certain requirements by adding metric filters. It uses the following format:

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

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() []Filters also work for dimensions in a comparable way, but the filter expressions will be slightly various due to the characteristic nature of measurements.

[]For example, if you only want to extract pageviews from users who have visited the site using the Chrome internet browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [], “measurements”: [], “dimensionFilterClauses”: []] ). perform()


[]As metrics are quantitative steps, there is likewise 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 instance, you can determine conclusions per user by dividing the variety of completions by the number of users.

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], “metrics”: [“expression”: “ga: goal1completions]] ). perform()


[]The API likewise lets you pail dimensions with an integer (numerical) value into ranges using pie chart pails.

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

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). perform() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a standard guide to accessing the Google Analytics API, composing some various requests, and gathering some significant insights in an easy-to-view format. I have actually added the build and request 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 further. More resources: Included Image: BestForBest/Best SMM Panel