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

  • Construct custom-made control panels to display GA data.
  • Automate complex reporting tasks.
  • Integrate with other applications.

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

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

[]I intend to write a follow-up guide exploring different ways you can examine, envision, and integrate the data.

Setting Up The API

Creating A Google Service Account

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

[]When this has actually been created, the next action is to pick the + Produce 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 produced, navigate to the KEYS area and add a new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a private secret. In this circumstances, select JSON, and after that develop and

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

Contribute To Google Analytics Account

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

Allowing The API The last and arguably crucial action is guaranteeing you have actually allowed access to the API. To do this, ensure you are in the appropriate job and follow this link to enable access.

[]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 prompted to finish 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 writing the []script to export the information. I chose Jupyter Notebooks to create this, but you can likewise use other integrated developer

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

Some are unique 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 build from oauth2client.service _ account import ServiceAccountCredentials! pip install connect! pip install functions import connect Note: When utilizing pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t needed. Developing 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 client tricks JSON download that was created when creating the private key. This

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

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

[]Finally, include the view ID from the analytics account with which you want 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 actually added our personal key file, we can include this to the credentials function by calling the file and setting it up through the ServiceAccountCredentials step.

[]Then, set up the build 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 = develop(‘analyticsreporting’, ‘v4’, qualifications=qualifications)

Composing The Demand Body

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

[]From the API service develop, there is the capability to choose the aspects from the response that we wish to access. 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 couple of things that are needed during this develop phase, starting with our viewId. As we have actually already defined formerly, we just require to call that function name (VIEW_ID) instead of adding the whole view ID again.

[]If you wanted to collect information from a different analytics see in the future, you would just need to alter the ID in the initial code block instead of both.

[]Date Variety

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

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

[]You can select defined 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 wish to view data from the last thirty days, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]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 attributes of users, their sessions, and their actions. For example, page path, traffic source, and keywords utilized.

[]There are a lot of various metrics and measurements that can be accessed. I will not go through all of them in this article, however they can all be discovered together with additional info and attributes here.

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

[]Both the metrics and dimensions are included a dictionary format, utilizing secret: value sets. 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 wanted 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 new users.

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

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

[]Integrating Dimensions And Metrics

[]The genuine worth is in combining metrics and dimensions to extract the key insights we are most interested in.

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [], ‘dimensions’: []] ). carry out()

Developing A DataFrame

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

[]To turn our response into a dataframe, we initially require to create 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 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(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement 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(worth)) []Including The Response Data

[]When the data remains in those lists, we can easily turn them into a dataframe by defining the column names, in square brackets, and appointing 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 Reaction Request Examples Multiple Metrics There is also the ability to integrate several metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise request the API response just returns metrics that return specific requirements by adding metric filters. It uses the following format:

if metricName operator return the metric []For instance, if you only wanted to draw out pageviews with more than ten views.

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

[]For instance, if you only wish to draw out pageviews from users who have actually checked out the site using the Chrome web browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

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


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

[]This involves specifying an alias to represent the expression and completing 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.

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


[]The API also lets you pail measurements with an integer (numeric) value into ranges utilizing histogram pails.

[]For example, bucketing the sessions count dimension into four 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.

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [], “dimensions”: [], “orderBys”: [“fieldName”: “ga: sessionCount”, “orderType”: “HISTOGRAM_BUCKET”]] ). perform() Screenshot from author, December 2022 In Conclusion I hope this has offered you with a basic guide to accessing the Google Analytics API, writing some different demands, and collecting some meaningful insights in an easy-to-view format. I have added the construct and ask for 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 data even more. More resources: Included Image: BestForBest/Best SMM Panel