How To Gain Access To Google Analytics API Via Python

Posted by

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

[]The main Google paperwork describes that it can be used to:

  • Construct custom-made dashboards to show GA data.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

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

[]This article will just cover a few of the approaches that can be utilized to access different subsets of data utilizing various metrics and dimensions.

[]I wish to write a follow-up guide exploring different methods you can evaluate, visualize, and integrate the data.

Setting Up The API

Producing A Google Service Account

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

[]As soon as this has been developed, the next action is to select 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 Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been developed, navigate to the KEYS section 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, choose JSON, and after that create and

await 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 email that has been created for the service account– this can be found on the primary account page.

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

Making it possible for The API The final and perhaps essential step is ensuring you have made it possible for access to the API. To do this, ensure you are in the appropriate job and follow this link to enable access.

[]Then, follow the actions 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 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 composing the []script to export the information. I picked Jupyter Notebooks to develop this, but you can likewise use other incorporated designer

[]environments(IDEs)including PyCharm or VSCode. Installing Libraries The initial step is to install the libraries that are needed to run the remainder of the code.

Some are special to the analytics API, and others are useful 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 set up link! pip set up 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 required. Developing 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 client secrets JSON download that was produced when creating the private key. This

[]is used in a comparable method to an API secret. 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.

[]Finally, add the view ID from the analytics account with which you wish to access the information. Screenshot from author, December 2022 Entirely

[]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 actually included our personal key file, we can include this to the qualifications function 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 already specified qualifications from above.

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

Writing The Request Body

[]Once we have whatever set up and defined, the real enjoyable begins.

[]From the API service construct, there is the capability to choose the aspects from the response that we wish 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 valid entry in the dateRanges field.
  • A minimum of one legitimate entry in the metrics field.

[]View ID

[]As pointed out, there are a couple of things that are needed during this develop stage, starting with our viewId. As we have actually already specified previously, we just require to call that function name (VIEW_ID) instead of including the whole view ID once again.

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

[]Date Range

[]Then we can add the date variety for the dates that we want to gather the data for. This includes a start date and an end date.

[]There are a number of methods to write this within the construct demand.

[]You can choose specified dates, for example, 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 want to see information from the last one month, you can set the start date as ’30daysAgo’ and completion 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.

[]Dimensions are the qualities of users, their sessions, and their actions. For example, page course, traffic source, and keywords utilized.

[]There are a lot of different metrics and dimensions that can be accessed. I won’t go through all of them in this short article, but they can all be found together with additional info and attributes here.

[]Anything you can access in Google Analytics you can access in the API. This consists of objective conversions, starts and values, the internet browser gadget used to access the site, landing page, second-page path tracking, and internal search, website speed, and audience metrics.

[]Both the metrics and measurements are included a dictionary format, using secret: value sets. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a particular format.

[]For example, if we wished to get a count of all sessions, we would add ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wished to see a count of all brand-new users.

[]With measurements, the key will be ‘name’ followed by the colon again and the worth of the dimension. For instance, if we wished to draw out the various page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Measurements And Metrics

[]The genuine value is in integrating metrics and dimensions to draw out the key insights we are most thinking about.

[]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 dimension to be ga: medium.

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

Creating A DataFrame

[]The reaction we obtain from the API remains in the form of a dictionary, with all of the data in key: value sets. To make the data easier to view and evaluate, we can turn it into a Pandas dataframe.

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

[]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 formerly 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(‘data’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘measurements’, [] 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)) []Including The Reaction Data

[]As soon as the information 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 Action Request Examples Numerous Metrics There is likewise the ability to combine multiple metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can also request the API reaction just returns metrics that return particular criteria by including metric filters. It uses the following format:

if metricName operator return the metric []For example, if you just wished to extract pageviews with more than ten views.

action = service.reports(). batchGet( body= ). carry out() []Filters also work for measurements in a similar way, but the filter expressions will be a little various due to the particular nature of measurements.

[]For example, if you just wish to draw out pageviews from users who have actually checked out the website using the Chrome internet browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


[]As metrics are quantitative measures, there is likewise the capability to compose expressions, which work similarly to determined metrics.

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

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

action = service.reports(). batchGet( body= ). execute()


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

[]For example, bucketing the sessions count measurement into 4 containers of 1-9, 10-99, 100-199, and 200-399, you can use the HISTOGRAM_BUCKET order type and define the varieties in histogramBuckets.

action = service.reports(). batchGet( body= ). perform() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a basic guide to accessing the Google Analytics API, writing some various demands, and collecting some meaningful insights in an easy-to-view format. I have actually included the build and request code, and the bits shared to this GitHub file. I will like to hear if you try any of these and your prepare for exploring []the data further. More resources: Featured Image: BestForBest/SMM Panel