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 official Google documents discusses that it can be used to:

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

[]You can access the API response utilizing numerous different techniques, including Java, PHP, and JavaScript, but this short article, in specific, will focus on accessing and exporting information utilizing Python.

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

[]I intend to write a follow-up guide checking out various methods you can examine, envision, and integrate the data.

Setting Up The API

Producing A Google Service Account

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

[]As soon as this has been developed, the next action is to pick the + Create Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to add 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 actually been produced, browse to the KEYS section and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a personal secret. In this circumstances, select JSON, and after that produce and

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

Add To Google Analytics Account

[]You will likewise want to take a copy of the e-mail that has actually 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 add that e-mail []as a user in Google Analytics with Analyst approvals. Screenshot from Google Analytics, December 2022

Enabling The API The last and arguably essential action is ensuring you have enabled access to the API. To do this, ensure you remain in the right task and follow this link to make it possible for gain access to.

[]Then, follow the actions to enable it when promoted.

Screenshot from Google Cloud, December 2022 This is required in order to access the API. If you miss this step, you will be prompted to finish it when very first running the script. Accessing The Google Analytics API With Python Now everything is set up in our service account, we can start writing the []script to export the data. I chose Jupyter Notebooks to produce this, but you can likewise use other integrated developer

[]environments(IDEs)consisting of PyCharm or VSCode. Setting up Libraries The initial 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 sections of the code.! pip set up– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip set up link! pip install functions import link Note: When using pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t required. Developing A Service Build The next step is to set []up our scope, which is the read-only analytics API authentication link. This is followed by the customer secrets JSON download that was created when producing the personal key. This

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

[]have actually saved 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 want to access the data. Screenshot from author, December 2022 Altogether

[]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 include this to the credentials operate by calling the file and setting it up through the ServiceAccountCredentials action.

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

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

Writing The Demand Body

[]Once we have everything established and defined, the genuine fun begins.

[]From the API service develop, there is the ability to pick the components from the response that we want to access. 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.
  • A minimum of one legitimate entry in the metrics field.

[]View ID

[]As discussed, there are a couple of things that are needed throughout this construct phase, starting with our viewId. As we have actually currently specified formerly, we just require to call that function name (VIEW_ID) instead of including the whole view ID once again.

[]If you wanted to collect data from a various analytics view in the future, you would just need to alter the ID in the initial code block rather than both.

[]Date Variety

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

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

[]You can select specified dates, for example, in between 2 dates, by adding the date in a year-month-date format, ‘startDate’: ‘2022-10-27’, ‘endDate’: ‘2022-11-27’.

[]Or, if you wish to see information from the last one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

[]The last step of the standard action call is setting the metrics and measurements. 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 instance, page path, traffic source, and keywords utilized.

[]There are a lot of different metrics and measurements that can be accessed. I won’t go through all of them in this post, however they can all be found together with additional information and associates here.

[]Anything you can access in Google Analytics you can access in the API. This includes goal conversions, starts and values, the browser device utilized 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 key: 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 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 measurements, the secret will be ‘name’ followed by the colon once again and the value of the measurement. For example, if we wanted to draw out the different page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Dimensions And Metrics

[]The real value is in integrating metrics and measurements to extract the crucial insights we are most interested in.

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: sessions’], ‘measurements’: []] ). carry out()

Producing A DataFrame

[]The reaction we get from the API remains in the type of a dictionary, with all of the information in secret: value sets. To make the data easier to see and analyze, we can turn it into a Pandas dataframe.

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

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

[]As soon as the data is in those lists, we can easily turn them into a dataframe by defining 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 Several Metrics There is also the capability to combine several metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can also ask for the API reaction only returns metrics that return specific criteria by adding metric filters. It uses the following format:

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

response = service.reports(). batchGet( body= ). execute() []Filters likewise work for dimensions in a similar method, but the filter expressions will be a little different due to the particular nature of measurements.

[]For instance, if you only want to extract pageviews from users who have actually checked out 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’: [‘expression’: ‘ga: pageviews’], “measurements”: [], “dimensionFilterClauses”: []] ). perform()


[]As metrics are quantitative measures, there is likewise the ability to compose expressions, which work likewise to computed metrics.

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

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

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


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

[]For instance, bucketing the sessions count dimension into 4 buckets of 1-9, 10-99, 100-199, and 200-399, you can use the HISTOGRAM_BUCKET order type and define the ranges in histogramBuckets.

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually supplied you with a standard guide to accessing the Google Analytics API, writing some various requests, and collecting some meaningful insights in an easy-to-view format. I have added the build and request code, and the bits shared to this GitHub file. I will enjoy to hear if you try any of these and your prepare for exploring []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel