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 customized dashboards to display GA data.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API response utilizing several various approaches, consisting of Java, PHP, and JavaScript, but this article, in particular, will concentrate on accessing and exporting data using Python.

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

[]I hope to compose a follow-up guide checking out different ways you can analyze, envision, and combine the information.

Establishing The API

Developing A Google Service Account

[]The primary step is to develop a task 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 Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been produced, navigate to the KEYS section and add a new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to develop and download a private key. In this instance, select JSON, and then produce and

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

Add To Google Analytics Account

[]You will also want 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 e-mail []as a user in Google Analytics with Expert authorizations. Screenshot from Google Analytics, December 2022

Allowing The API The final and perhaps crucial step is ensuring you have actually allowed access to the API. To do this, guarantee you remain in the appropriate job 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 required in order to access the API. If you miss this step, you will be prompted to complete it when first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can begin writing the []script to export the data. I selected Jupyter Notebooks to create this, but you can likewise utilize other integrated developer

[]environments(IDEs)including PyCharm or VSCode. Setting up Libraries The primary step is to set up the libraries that are needed 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 set up– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip set up functions import connect Note: When utilizing pip in a Jupyter note pad, add the!– if running in the command line or another IDE, the! isn’t required. Producing 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 customer tricks JSON download that was generated when producing the personal key. This

[]is utilized in a similar method to an API key. To easily access this file within your code, guarantee you

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

[]Lastly, add the view ID from the analytics account with which you wish to access the data. 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 actually included our personal essential file, we can add this to the credentials operate by calling the file and setting it up through the ServiceAccountCredentials action.

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

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

Writing The Demand Body

[]Once we have whatever set up and defined, the genuine fun begins.

[]From the API service develop, there is the capability to choose the components from the action that we wish to access. This is called a ReportRequest object and needs the following as a minimum:

  • A valid view ID for the viewId field.
  • At least one legitimate entry in the dateRanges field.
  • A minimum of one valid entry in the metrics field.

[]View ID

[]As discussed, there are a couple of things that are needed throughout this construct stage, beginning with our viewId. As we have actually already defined formerly, we just require to call that function name (VIEW_ID) rather than including the whole view ID once again.

[]If you wanted to gather data from a different analytics view in the future, you would simply require to change the ID in the preliminary code block rather than both.

[]Date Range

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

[]There are a couple of ways to compose this within the build demand.

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

[]Metrics And Dimensions

[]The last step of the fundamental action 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 attributes of users, their sessions, and their actions. For example, page path, traffic source, and keywords used.

[]There are a great deal of different metrics and dimensions that can be accessed. I will not go through all of them in this post, 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 web browser device 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 added in a dictionary format, using secret: worth sets. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a specific format.

[]For instance, if we wished to get a count of all sessions, we would add ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wanted 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 wished to extract the various page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Integrating Dimensions And Metrics

[]The genuine worth is in combining metrics and measurements to draw out the key insights we are most interested in.

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

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

Developing A DataFrame

[]The response we receive from the API remains in the kind of a dictionary, with all of the data in key: worth sets. To make the information simpler to view and analyze, 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 reaction output, we will append the data from the measurements 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(‘data’, ). get(‘rows’, [] for row in rows: measurements = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Adding The Reaction Data

[]When the information remains 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= "" alt="DataFrame Example"/ > More Response Demand Examples Numerous Metrics There is also the capability to integrate several metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can also request the API action just returns metrics that return specific criteria by including metric filters. It uses the following format:

if return the metric []For example, if you only wished to extract pageviews with more than 10 views.

action = service.reports(). batchGet( body= ). carry out() []Filters also work for dimensions in a comparable method, but the filter expressions will be somewhat different due to the characteristic nature of dimensions.

[]For instance, if you only want to extract pageviews from users who have gone to the site using the Chrome internet browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

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


[]As metrics are quantitative measures, there is likewise the ability to write expressions, which work likewise to determined metrics.

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

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

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


[]The API likewise lets you pail measurements with an integer (numerical) worth into varieties utilizing histogram pails.

[]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 specify the ranges in histogramBuckets.

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