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 documents describes that it can be utilized to:

  • Construct custom-made dashboards to show GA information.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API reaction utilizing numerous various techniques, including Java, PHP, and JavaScript, but this article, in particular, will focus on accessing and exporting data using Python.

[]This article will simply cover some of the approaches that can be used to access various subsets of data using various metrics and measurements.

[]I want to compose a follow-up guide exploring various ways you can examine, envision, and integrate the information.

Setting Up The API

Producing A Google Service Account

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

[]As soon as this has been created, the next step is to select the + Produce 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 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 been created, browse to the secret area and include a new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a personal key. In this instance, choose JSON, and after that create and

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

Add To Google Analytics Account

[]You will likewise wish to take a copy of the email that has been produced for the service account– this can be discovered on the primary account page.

Screenshot from Google Cloud, December 2022 The next action is to include that email []as a user in Google Analytics with Analyst authorizations. Screenshot from Google Analytics, December 2022

Enabling The API The last and probably most important step is ensuring you have actually enabled access to the API. To do this, ensure you are in the proper 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 required in order to access the API. If you miss this step, you will be triggered 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 composing the []script to export the information. I chose Jupyter Notebooks to develop this, however you can likewise utilize other incorporated developer

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

Some are special to the analytics API, and others work for future sections of the code.! pip set up– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip set up connect! pip install functions import link Note: When using pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t required. Producing A Service Develop The next action 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 developing the personal key. This

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

[]have saved the JSON file in the exact 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 actually 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, established the build 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’, qualifications=qualifications)

Composing The Demand Body

[]As soon as we have whatever established and specified, the real enjoyable starts.

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

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

[]View ID

[]As pointed out, there are a couple of things that are required during this develop stage, beginning with our viewId. As we have actually already defined previously, we just need to call that function name (VIEW_ID) rather than adding the entire view ID once again.

[]If you wanted to collect data from a different analytics view in the future, you would just require to alter the ID in the initial 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 number of methods to write this within the construct demand.

[]You can select specified dates, for example, between two 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 data from the last one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The last step of the basic reaction call is setting the metrics and measurements. 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 instance, page path, traffic source, and keywords utilized.

[]There are a great deal of various metrics and dimensions that can be accessed. I will not go through all of them in this short article, but they can all be discovered together with extra 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 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 key: worth pairs. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and after that the value 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 dimensions, the secret will be ‘name’ followed by the colon once again and the value of the measurement. For example, if we wanted to draw out the different page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The real value is in combining metrics and dimensions to extract the essential insights we are most thinking about.

[]For instance, 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 measurement to be ga: medium.

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

Developing A DataFrame

[]The reaction we get from the API remains in the type of a dictionary, with all of the information in key: value pairs. To make the data much easier to see and analyze, we can turn it into a Pandas dataframe.

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

[]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 draw out the data and include it to our previously 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, measurement in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Including The Action Data

[]As soon as the data remains in those lists, we can quickly turn them into a dataframe by defining the column names, in square brackets, and assigning 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 Response Request Examples Multiple Metrics There is likewise the capability to combine multiple metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can likewise request the API reaction just returns metrics that return certain criteria by including metric filters. It utilizes the following format:

if operator return the metric []For example, if you just wished to draw out pageviews with more than 10 views.

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

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [], “dimensions”: [“name”: “ga: internet browser”], “dimensionFilterClauses”: [“filters”: []]] ). execute()

Expressions

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

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

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

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

Histograms

[]The API likewise lets you container dimensions with an integer (numerical) worth into ranges using pie chart containers.

[]For instance, bucketing the sessions count measurement into 4 containers of 1-9, 10-99, 100-199, and 200-399, you can utilize the HISTOGRAM_BUCKET order type and specify the ranges in histogramBuckets.

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [], “measurements”: [], “orderBys”: [“fieldName”: “ga: sessionCount”, “orderType”: “HISTOGRAM_BUCKET”]] ). perform() Screenshot from author, December 2022 In Conclusion I hope this has offered you with a fundamental guide to accessing the Google Analytics API, writing some different requests, and gathering some significant insights in an easy-to-view format. I have actually added the develop and request code, and the bits shared to this GitHub file. I will enjoy 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