How To Access 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 official Google documentation discusses that it can be utilized to:

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

[]You can access the API action using a number of different techniques, consisting of Java, PHP, and JavaScript, but this short article, in specific, will focus on accessing and exporting data using Python.

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

[]I hope to write a follow-up guide checking out various methods you can analyze, envision, and integrate the information.

Establishing The API

Creating A Google Service Account

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

[]When this has been produced, the next action is to select the + Develop 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= "// www.w3.org/2000/svg%22%20viewBox=%220%200%201152%201124%22%3E%3C/svg%3E"alt="Service Account Details"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 developed, navigate to the KEYS area and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to produce and download a personal secret. In this instance, choose JSON, and then produce and

wait for 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 e-mail that has been generated for the service account– this can be found on the primary account page.

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

Making it possible for The API The last and perhaps essential step is ensuring you have enabled access to the API. To do this, guarantee you remain in the right project 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 triggered 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 data. I selected Jupyter Notebooks to develop this, however you can also utilize other incorporated designer

[]environments(IDEs)consisting of PyCharm or VSCode. Setting up Libraries The first step is to set up the libraries that are required to run the remainder of the code.

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

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

[]have conserved 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 would like to access the data. Screenshot from author, December 2022 Entirely

[]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 added our private crucial file, we can include this to the credentials 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 currently specified qualifications from above.

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

Writing The Request Body

[]Once we have whatever established and specified, the genuine fun starts.

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

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

[]View ID

[]As pointed out, there are a couple of things that are needed during this construct stage, starting with our viewId. As we have actually already defined formerly, we simply require to call that function name (VIEW_ID) rather than adding the whole view ID again.

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

[]Date Variety

[]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 write this within the construct request.

[]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 view data from the last 1 month, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Measurements

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

[]Dimensions are the qualities of users, their sessions, and their actions. For instance, page course, traffic source, and keywords used.

[]There are a lot of different metrics and dimensions that can be accessed. I will not go through all of them in this short article, however they can all be found together with additional info and associates here.

[]Anything you can access in Google Analytics you can access in the API. This includes objective conversions, starts and values, the internet browser device utilized to access the site, landing page, second-page path tracking, and internal search, site speed, and audience metrics.

[]Both the metrics and measurements are added in a dictionary format, using secret: worth pairs. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and after that the worth of our metric, which will have a particular format.

[]For example, if we wished 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 key will be ‘name’ followed by the colon again and the value of the measurement. 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 website.

[]Combining Measurements And Metrics

[]The real worth is in combining metrics and measurements to extract the essential insights we are most interested in.

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

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

Producing A DataFrame

[]The reaction we receive from the API is in the type of a dictionary, with all of the data in secret: value sets. To make the data much easier to see and analyze, we can turn it into a Pandas dataframe.

[]To turn our response into a dataframe, we first require to develop some empty lists, to hold the metrics and measurements.

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

[]As soon as 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= "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 Numerous Metrics There is also the ability to combine numerous metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can likewise request the API response just returns metrics that return specific requirements by adding metric filters. It utilizes the following format:

if metricName comparisonValue return the metric []For instance, if you only wished to extract pageviews with more than ten views.

response = service.reports(). batchGet( body= ). carry out() []Filters also work for measurements in a similar way, however the filter expressions will be slightly different due to the particular nature of measurements.

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

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

Expressions

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

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

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [“expression”: “ga: goal1completions]] ). execute()

Histograms

[]The API also lets you pail measurements with an integer (numerical) worth into varieties utilizing pie chart containers.

[]For instance, bucketing the sessions count dimension into four buckets of 1-9, 10-99, 100-199, and 200-399, you can utilize the HISTOGRAM_BUCKET order type and define the ranges in histogramBuckets.

reaction = service.reports(). batchGet( body= ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually offered you with a standard guide to accessing the Google Analytics API, writing some different demands, and gathering some meaningful insights in an easy-to-view format. I have actually included the construct and request code, and the snippets shared to this GitHub file. I will like to hear if you try any of these and your prepare for exploring []the information further. More resources: Included Image: BestForBest/Best SMM Panel