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

  • Build custom control panels to show GA data.
  • Automate complex reporting tasks.
  • Integrate with other applications.

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

[]This article will just cover some of the methods that can be used to access various subsets of data using various metrics and dimensions.

[]I hope to compose a follow-up guide exploring different ways you can evaluate, picture, and integrate the information.

Establishing The API

Developing A Google Service Account

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

[]As soon as this has been produced, the next step is to choose the + Develop 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= "// www.w3.org/2000/svg%22%20viewBox=%220%200%201152%201124%22%3E%3C/svg%3E"alt="Service Account Particulars"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 actually been created, navigate to the secret area and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a personal key. In this instance, choose JSON, and after that create and

await 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 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 add that email []as a user in Google Analytics with Expert consents. Screenshot from Google Analytics, December 2022

Making it possible for The API The last and arguably essential action is guaranteeing you have actually enabled access to the API. To do this, ensure you are in the correct project and follow this link to allow gain access to.

[]Then, follow the steps to enable it when promoted.

Screenshot from Google Cloud, December 2022 This is needed in order to access the API. If you miss this action, you will be prompted to finish it when first running the script. Accessing The Google Analytics API With Python Now everything is established in our service account, we can start writing the []script to export the data. I chose Jupyter Notebooks to create this, but you can likewise utilize other integrated developer

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

Some are unique to the analytics API, and others are useful for future areas of the code.! pip install– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip install connect! pip set up 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. Developing A Service Build The next step is to set []up our scope, which is the read-only analytics API authentication link. This is followed by the customer secrets JSON download that was generated when creating the personal secret. This

[]is utilized in a similar way to an API key. To quickly 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.

[]Lastly, include the view ID from the analytics account with which you wish to access the data. Screenshot from author, December 2022 Altogether

[]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 private crucial file, we can include this to the qualifications function by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, established the build report, calling the analytics reporting API V4, and our currently specified credentials from above.

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

Writing The Request Body

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

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

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

[]View ID

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

[]If you wanted to collect information from a different analytics view in the future, you would just need to change the ID in the preliminary code block rather than both.

[]Date Range

[]Then we can add the date variety for the dates that we want to collect the information for. This includes a start date and an end date.

[]There are a couple of methods to compose this within the build request.

[]You can pick 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 one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The last action of the standard reaction call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session duration, and bounce rate.

[]Measurements are the qualities of users, their sessions, and their actions. For example, page course, 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, but they can all be discovered together with extra information and associates here.

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

[]Both the metrics and measurements are added in a dictionary format, utilizing 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 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 wanted to see a count of all new users.

[]With measurements, the key will be ‘name’ followed by the colon again and the worth 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 different traffic source referrals to the site.

[]Combining Dimensions And Metrics

[]The real value is in combining metrics and measurements to draw out the crucial insights we are most interested in.

[]For example, to see a count of all sessions that have been created 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= ). perform()

Creating A DataFrame

[]The reaction we get from the API remains in the type of a dictionary, with all of the data in secret: worth sets. To make the information simpler to view and evaluate, we can turn it into a Pandas dataframe.

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

[]Then, calling the reaction output, we will append the information 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 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(‘data’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘worths’)): metric.append(int(worth)) []Adding The Action Data

[]As soon as the information is in those lists, we can quickly turn them into a dataframe by specifying the column names, in square brackets, and assigning the list values 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 Response Request Examples Several Metrics There is also the ability to integrate multiple metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can likewise request the API reaction only returns metrics that return particular criteria by adding metric filters. It utilizes the following format:

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [], ‘measurements’: [‘name’: ‘ga: pagePath’], “metricFilterClauses”: []] ). execute() []Filters also work for measurements in a comparable way, however the filter expressions will be a little different due to the characteristic nature of dimensions.

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

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [], “dimensions”: [“name”: “ga: browser”], “dimensionFilterClauses”: [“filters”: [“dimensionName”: “ga: web browser”, “operator”: “EXACT”, “expressions”: [” Chrome”]]]] ). perform()

Expressions

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

[]This involves defining 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 number of completions by the number of users.

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

Histograms

[]The API also lets you container measurements with an integer (numeric) worth into ranges utilizing histogram containers.

[]For instance, bucketing the sessions count dimension into four pails of 1-9, 10-99, 100-199, and 200-399, you can use the HISTOGRAM_BUCKET order type and specify the varieties in histogramBuckets.

reaction = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has offered you with a standard guide to accessing the Google Analytics API, composing some different demands, and collecting some significant insights in an easy-to-view format. I have added the develop and request code, and the bits shared to this GitHub file. I will like to hear if you try any of these and your plans for exploring []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel