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

  • Develop custom dashboards to display GA data.
  • Automate complex reporting tasks.
  • Incorporate with other applications.

[]You can access the API response using a number of different approaches, consisting of Java, PHP, and JavaScript, but this article, in specific, will focus on accessing and exporting data using Python.

[]This post will just cover a few of the techniques that can be utilized to gain access to various subsets of data using different metrics and dimensions.

[]I want to compose a follow-up guide exploring various methods you can evaluate, imagine, and integrate the data.

Establishing The API

Creating A Google Service Account

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

[]Once this has been developed, 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 Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been developed, navigate to the secret section and add a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a private key. In this circumstances, choose JSON, and after that develop and

wait for 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 actually been produced for the service account– this can be found on the main account page.

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

Making it possible for The API The final and perhaps most important step is ensuring you have allowed access to the API. To do this, guarantee you are in the correct job and follow this link to allow gain access to.

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

Screenshot from Google Cloud, December 2022 This is required in order to access the API. If you miss this action, you will be prompted to complete it when very first running the script. Accessing The Google Analytics API With Python Now everything is established in our service account, we can begin composing the []script to export the information. I selected Jupyter Notebooks to create this, but you can likewise utilize other incorporated designer

[]environments(IDEs)consisting of PyCharm or VSCode. Setting up 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 sections 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 connect! pip set up functions import link 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 Develop The next action 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 generated when producing the private key. This

[]is used in a comparable way to an API key. To easily access this file within your code, guarantee you

[]have saved the JSON file in the same folder as the code file. This can then quickly be called with the KEY_FILE_LOCATION function.

[]Finally, include the view ID from the analytics account with which you would like to access the information. Screenshot from author, December 2022 Altogether

[]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 qualifications function by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, established the develop 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=credentials)

Writing The Request Body

[]As soon as we have whatever set up and defined, the real enjoyable starts.

[]From the API service develop, there is the capability to pick the components from the response that we wish to access. This is called a ReportRequest object and requires 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 discussed, there are a couple of things that are required throughout this build stage, starting with our viewId. As we have actually already defined formerly, we just need to call that function name (VIEW_ID) instead of adding the whole view ID again.

[]If you wanted to collect data from a various analytics view in the future, you would simply need to alter the ID in the preliminary code block instead of both.

[]Date Variety

[]Then we can add the date range for the dates that we want to gather the information for. This consists of a start date and an end date.

[]There are a couple of ways to write this within the construct demand.

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

[]Or, if you want to see data from the last 30 days, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The last action of the basic action 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 example, page path, traffic source, and keywords utilized.

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

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

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

[]With dimensions, the secret will be ‘name’ followed by the colon once again and the worth of the dimension. For instance, if we wanted to extract the various page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Measurements And Metrics

[]The genuine value is in combining metrics and measurements to extract the crucial 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 dimension to be ga: medium.

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

Developing A DataFrame

[]The action we obtain from the API remains in the kind of a dictionary, with all of the information in secret: value pairs. To make the data easier to view and examine, we can turn it into a Pandas dataframe.

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

[]Then, calling the action 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 data and add it to our previously 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(‘information’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, measurements): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘worths’)): metric.append(int(value)) []Including The Reaction 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 appointing 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 Numerous Metrics There is also the capability to combine numerous metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can also ask for the API action only returns metrics that return certain criteria by adding metric filters. It utilizes the following format:

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

action = service.reports(). batchGet( body= ). execute() []Filters also work for dimensions in a comparable way, however the filter expressions will be slightly various due to the particular nature of measurements.

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

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


[]As metrics are quantitative steps, there is also the capability to compose expressions, which work likewise to calculated metrics.

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

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

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


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

[]For example, bucketing the sessions count dimension into four pails 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= ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually offered you with a basic guide to accessing the Google Analytics API, writing some different requests, and collecting some significant insights in an easy-to-view format. I have actually included the develop and request code, and the bits shared to this GitHub file. I will enjoy to hear if you attempt any of these and your prepare for checking out []the information further. More resources: Featured Image: BestForBest/Best SMM Panel