How To Gain Access To 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 describes that it can be utilized to:

  • Build custom control panels to display GA information.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

[]You can access the API response utilizing several different methods, consisting of Java, PHP, and JavaScript, however this short article, in particular, will concentrate on accessing and exporting data utilizing Python.

[]This post will just cover some of the methods that can be used to gain access to different subsets of information utilizing various metrics and dimensions.

[]I hope to write a follow-up guide exploring different methods you can evaluate, envision, and integrate the information.

Setting Up The API

Producing A Google Service Account

[]The primary step is to produce a job or choose one within your Google Service Account.

[]As soon as this has been produced, 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 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 actually been created, navigate to the KEYS area and include a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a private secret. In this circumstances, choose JSON, and after that produce and

await 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 produced 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 e-mail []as a user in Google Analytics with Analyst authorizations. Screenshot from Google Analytics, December 2022

Making it possible for The API The final and arguably essential action is ensuring you have actually enabled access to the API. To do this, ensure you are in the proper project and follow this link to allow gain access to.

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

[]environments(IDEs)consisting of PyCharm or VSCode. Setting up Libraries The first step is to install the libraries that are needed 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 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. Creating 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 customer tricks JSON download that was created when producing the personal secret. This

[]is used in a similar way 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 easily be called with the KEY_FILE_LOCATION function.

[]Finally, add 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 added our private crucial file, we can add 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 already defined credentials from above.

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

Writing The Demand Body

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

[]From the API service develop, there is the capability to select the elements from the reaction that we wish to gain access to. This is called a ReportRequest object and needs the following as a minimum:

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

[]View ID

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

[]If you wanted to gather data from a various analytics view in the future, you would simply require to change the ID in the initial code block rather than both.

[]Date Range

[]Then we can include the date variety for the dates that we wish to gather the information for. This consists of a start date and an end date.

[]There are a number of ways to compose this within the build request.

[]You can select specified 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 data from the last 1 month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Measurements

[]The final step of the basic action 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 attributes of users, their sessions, and their actions. For example, page path, traffic source, and keywords utilized.

[]There are a lot of various metrics and dimensions that can be accessed. I will not go through all of them in this article, 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 objective conversions, begins and values, the internet browser device used to access the site, landing page, second-page path tracking, and internal search, site speed, and audience metrics.

[]Both the metrics and dimensions are added in a dictionary format, utilizing key: worth sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and after that the worth of our metric, which will have a particular format.

[]For instance, 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 value of the measurement. For example, if we wished to draw out the various page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Measurements And Metrics

[]The real value remains in integrating metrics and measurements to draw out the essential insights we are most thinking about.

[]For example, to see a count of all sessions that have been created from different traffic sources, we can set our metric to be ga: sessions and our measurement to be ga: medium.

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

Producing A DataFrame

[]The response we receive from the API remains in the kind of a dictionary, with all of the data in secret: value pairs. To make the data simpler to view and analyze, we can turn it into a Pandas dataframe.

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

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

[]When the data remains in those lists, we can easily 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 Response Demand Examples Numerous Metrics There is likewise the ability to integrate multiple metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can likewise ask for the API response just returns metrics that return particular criteria by including metric filters. It uses the following format:

if metricName return the metric []For instance, if you just wanted to extract pageviews with more than 10 views.

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

[]For instance, if you only wish to draw out pageviews from users who have actually checked out the site utilizing the Chrome web 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 also the ability to compose expressions, which work similarly to computed metrics.

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

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

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


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

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

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