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

  • Develop custom dashboards to show GA information.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

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

[]This short article will just cover a few of the techniques that can be used to gain access to different subsets of information using different metrics and dimensions.

[]I want to write a follow-up guide checking out different ways you can evaluate, envision, and integrate the information.

Setting Up The API

Developing A Google Service Account

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

[]Once this has been developed, 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 information such as a name, ID, and description.< img src= "// www.w3.org/2000/svg%22%20viewBox=%220%200%201152%201124%22%3E%3C/svg%3E"alt="Service Account Details"width="1152"height=" 1124"data-src="https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-12-at-20.20.21-639b81474320f-sej.png"/ > Screenshot from Google Cloud, December 2022 Once the service account has been developed, browse to the secret area and include a brand-new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a private key. In this instance, select JSON, and then develop and

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

Contribute To Google Analytics Account

[]You will also wish to take a copy of the e-mail that has been created for the service account– this can be discovered on the primary account page.

Screenshot from Google Cloud, December 2022 The next step is to include that email []as a user in Google Analytics with Expert consents. Screenshot from Google Analytics, December 2022

Allowing The API The last and arguably most important step is guaranteeing you have actually enabled access to the API. To do this, guarantee you are in the proper project and follow this link to enable gain access to.

[]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 step, 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 data. I picked Jupyter Notebooks to develop this, however you can likewise use other incorporated developer

[]environments(IDEs)consisting of PyCharm or VSCode. Putting up Libraries The primary step is to set up 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 areas of the code.! pip set up– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip set up functions import link Note: When utilizing pip in a Jupyter notebook, 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 client tricks JSON download that was produced when producing the personal secret. This

[]is used in a similar way to an API secret. To quickly access this file within your code, guarantee you

[]have 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 wish to access the information. Screenshot from author, December 2022 Entirely

[]this will look like the following. We will reference these functions throughout our code.

SCOPES = [‘ https://www.googleapis.com/auth/analytics.readonly’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have included our personal crucial file, we can include this to the qualifications function by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, set up the develop report, calling the analytics reporting API V4, and our currently specified qualifications from above.

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

Composing The Demand Body

[]When we have everything set up and defined, the real enjoyable begins.

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

  • A valid view ID for the viewId field.
  • At least one valid 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 develop phase, beginning with our viewId. As we have currently defined formerly, we just require to call that function name (VIEW_ID) instead of adding the whole view ID again.

[]If you wished to gather 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 include the date range for the dates that we want to collect the data for. This consists of a start date and an end date.

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

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

[]Or, if you wish to view information from the last thirty 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 dimensions. Metrics are the quantitative measurements from Google Analytics, such as session count, session period, and bounce rate.

[]Dimensions are the qualities of users, their sessions, and their actions. For example, page path, 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, however they can all be discovered together with additional info 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 utilized to access the website, landing page, second-page course tracking, and internal search, site speed, and audience metrics.

[]Both the metrics and dimensions are included a dictionary format, using secret: value sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a particular 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 wished to see a count of all brand-new users.

[]With measurements, the key will be ‘name’ followed by the colon once again and the value of the dimension. For example, if we wished to extract the various 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 genuine value is in combining metrics and measurements to draw out the essential insights we are most interested in.

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

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

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 pairs. To make the information simpler to view and examine, we can turn it into a Pandas dataframe.

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

[]Then, calling the response output, we will append 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 include 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(‘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(‘values’)): metric.append(int(worth)) []Adding The Reaction Data

[]When the data is in those lists, we can quickly turn them into a dataframe by defining the column names, in square brackets, and designating the list worths to each column.

df = pd.DataFrame() df [” Sessions”] = metric df [” Medium”] = dim df= df [[ “Medium”,”Sessions”]] df.head()

< img src= "https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-13-at-20.30.15-639b817e87a2c-sej.png" alt="DataFrame Example"/ > More Reaction Demand Examples Numerous Metrics There is likewise the capability to integrate numerous metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can likewise request the API response 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 wished to draw out pageviews with more than ten views.

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). execute() []Filters also work for measurements in a similar way, however the filter expressions will be somewhat various due to the characteristic nature of dimensions.

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

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

Expressions

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

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

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

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

Histograms

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

[]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.

reaction = service.reports(). batchGet( body= ). execute() 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 various demands, and collecting some significant insights in an easy-to-view format. I have actually added the construct and ask for code, and the bits shared to this GitHub file. I will love to hear if you try any of these and your prepare for checking out []the data further. More resources: Included Image: BestForBest/SMM Panel