How To Gain Access To Google Analytics API Via Python

Posted by

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

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

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

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

[]This short article will simply cover some of the techniques that can be utilized to access different subsets of information utilizing various metrics and dimensions.

[]I wish to write a follow-up guide checking out different methods you can examine, envision, and combine 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 created, the next step is to choose the + Create Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to add some details 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 created, navigate to the KEYS area and add a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a private secret. In this circumstances, select JSON, and then create and

wait on 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 created for the service account– this can be found on the primary account page.

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

Making it possible for The API The last and perhaps most important action is guaranteeing you have enabled access to the API. To do this, ensure you are in the proper project and follow this link to allow access.

[]Then, follow the actions to enable 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 very first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can start composing the []script to export the information. I picked Jupyter Notebooks to develop this, but you can also utilize other incorporated developer

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

Some are distinct 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 build from oauth2client.service _ account import ServiceAccountCredentials! pip install link! 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. Producing A Service Develop 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 created when creating the personal key. This

[]is utilized in a comparable way to an API key. 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, add the view ID from the analytics account with which you want to access the information. Screenshot from author, December 2022 Completely

[]this will look 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 personal key file, we can add this to the qualifications work 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 already defined credentials from above.

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

Writing The Request Body

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

[]From the API service construct, there is the capability to choose the elements from the action that we want to gain access to. This is called a ReportRequest item 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.
  • At least one legitimate entry in the metrics field.

[]View ID

[]As discussed, there are a couple of things that are needed during this build stage, starting with our viewId. As we have currently defined previously, we just need to call that function name (VIEW_ID) instead of including the whole view ID again.

[]If you wanted to collect information from a various analytics see in the future, you would just 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 collect the data for. This includes a start date and an end date.

[]There are a couple of methods to write this within the develop demand.

[]You can choose defined dates, for instance, in 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 data from the last one month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Measurements

[]The last action of the standard response 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 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 measurements that can be accessed. I will not go through all of them in this post, but 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 consists of objective conversions, begins and values, the web 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: worth pairs. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the value of our metric, which will have a particular 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 again and the value of the dimension. For instance, if we wanted to draw out the different page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Measurements And Metrics

[]The genuine worth is in combining metrics and dimensions to draw out the crucial insights we are most thinking about.

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [] ). execute()

Developing A DataFrame

[]The response we receive from the API remains in the kind of a dictionary, with all of the information in key: value sets. To make the information easier to view and analyze, we can turn it into a Pandas dataframe.

[]To turn our response into a dataframe, we initially need to create 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 dimensions list and a count of the metrics into the metrics list.

[]This will extract the data and add 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(‘information’, ). get(‘rows’, [] for row in rows: measurements = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, dimensions): dim.append(dimension) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘worths’)): metric.append(int(worth)) []Including The Reaction Data

[]As soon as the data is 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 Action Request Examples Several Metrics There is likewise the ability to combine multiple 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 particular requirements by adding metric filters. It utilizes the following format:

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [‘expression’: ‘ga: pageviews’], ‘measurements’: [], “metricFilterClauses”: []] ). execute() []Filters likewise work for dimensions in a comparable way, but the filter expressions will be slightly different due to the characteristic nature of measurements.

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

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


[]As metrics are quantitative steps, there is likewise 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 two 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= ). perform()


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

[]For instance, bucketing the sessions count measurement 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.

response = service.reports(). batchGet( body= ). perform() 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 demands, and gathering some significant insights in an easy-to-view format. I have included the construct and request 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 information even more. More resources: Included Image: BestForBest/Best SMM Panel