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

  • Build custom control panels to show GA information.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API response using several different approaches, including Java, PHP, and JavaScript, but this article, in specific, will concentrate on accessing and exporting data using Python.

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

[]I hope to compose a follow-up guide exploring different methods you can examine, picture, and combine the information.

Setting Up The API

Producing A Google Service Account

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

[]When this has actually been created, the next action is to choose 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 Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been developed, navigate to the KEYS area and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a personal key. In this instance, select JSON, and then create and

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

Add To Google Analytics Account

[]You will likewise wish 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 include that email []as a user in Google Analytics with Analyst permissions. Screenshot from Google Analytics, December 2022

Making it possible for The API The last and perhaps crucial action is ensuring you have made it possible for access to the API. To do this, guarantee you remain in the correct job and follow this link to enable gain access to.

[]Then, follow the steps to allow 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 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 writing the []script to export the data. I selected Jupyter Notebooks to develop this, but you can also use other incorporated designer

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

Some are unique 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 install connect! pip install functions import connect Note: When utilizing pip in a Jupyter notebook, add the!– if running in the command line or another IDE, the! isn’t needed. Creating 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 secrets JSON download that was generated when producing the private key. This

[]is utilized in a similar method to an API key. To easily 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 easily 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 information. Screenshot from author, December 2022 Completely

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

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

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

Writing The Demand Body

[]As soon as we have everything established and defined, the genuine fun starts.

[]From the API service construct, there is the ability to pick the aspects from the response that we want to gain access to. 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 valid entry in the metrics field.

[]View ID

[]As pointed out, there are a few things that are required throughout this build phase, starting with our viewId. As we have actually already specified formerly, we simply require to call that function name (VIEW_ID) rather than adding the whole view ID once again.

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

[]Date Variety

[]Then we can add the date range for the dates that we wish to collect the data for. This includes a start date and an end date.

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

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

[]Metrics And Measurements

[]The final action of the fundamental action call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session period, and bounce rate.

[]Measurements are the characteristics of users, their sessions, and their actions. For example, page path, traffic source, and keywords used.

[]There are a great deal of various metrics and measurements that can be accessed. I will not go through all of them in this short article, but they can all be discovered together with extra details and associates here.

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

[]Both the metrics and dimensions are added in a dictionary format, using key: value pairs. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and after that the value of our metric, which will have a specific 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 measurements, the secret will be ‘name’ followed by the colon again and the worth of the dimension. For example, if we wanted to extract the different page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Measurements And Metrics

[]The real value remains in combining metrics and measurements to extract the essential insights we are most interested in.

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

Developing A DataFrame

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

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

[]Then, calling the action output, we will add 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 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(‘data’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘dimensions’, [] 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(‘values’)): metric.append(int(worth)) []Adding The Response Data

[]When the data is in those lists, we can easily turn them into a dataframe by specifying the column names, in square brackets, and assigning 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 Reaction Demand Examples Multiple Metrics There is also the ability to integrate multiple metrics, with each set added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can also ask for the API action only returns metrics that return specific criteria by adding metric filters. It utilizes the following format:

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

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

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

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


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

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


[]The API likewise lets you container dimensions with an integer (numeric) worth into ranges using pie chart pails.

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

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