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 official Google paperwork discusses that it can be used to:

  • Build custom-made control panels to show GA information.
  • Automate complex reporting tasks.
  • Incorporate with other applications.

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

[]This short article will just cover a few of the techniques that can be utilized to access various subsets of information using various metrics and dimensions.

[]I hope to write a follow-up guide exploring different ways you can analyze, imagine, and integrate the information.

Establishing The API

Creating 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 actually been developed, the next action is to select 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 Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been produced, navigate to the KEYS area and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to develop and download a private secret. In this circumstances, select JSON, and then create and

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

Contribute To Google Analytics Account

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

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

Making it possible for The API The final and probably most important action is ensuring you have actually allowed access to the API. To do this, guarantee you remain in the proper job and follow this link to make it possible for access.

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

Screenshot from Google Cloud, December 2022 This is needed 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 everything is established in our service account, we can begin composing the []script to export the information. I selected Jupyter Notebooks to create this, but you can also utilize other integrated 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 distinct to the analytics API, and others are useful for future areas of the code.! pip set up– 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 using pip in a Jupyter notebook, add the!– if running in the command line or another IDE, the! isn’t required. Developing A Service Construct 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 produced when developing the personal secret. This

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

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

[]Finally, include the view ID from the analytics account with which you wish 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 = [‘’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have included our personal essential file, we can include this to the qualifications operate by calling the file and setting it up through the ServiceAccountCredentials step.

[]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’, credentials=credentials)

Composing The Demand Body

[]When we have everything established and defined, the genuine fun begins.

[]From the API service construct, there is the capability to pick the aspects from the action that we wish to gain access to. This is called a ReportRequest things and requires the following as a minimum:

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

[]View ID

[]As pointed out, there are a few things that are needed throughout this construct phase, beginning with our viewId. As we have actually currently specified formerly, we simply require to call that function name (VIEW_ID) rather than including the entire view ID once again.

[]If you wished to gather data from a various analytics see in the future, you would just require to alter the ID in the preliminary code block instead of both.

[]Date Variety

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

[]There are a number of methods to compose this within the develop request.

[]You can pick defined dates, for example, 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 basic response 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 various metrics and dimensions that can be accessed. I won’t go through all of them in this short article, however 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 consists of goal conversions, starts and values, the web browser gadget 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 included a dictionary format, utilizing key: value sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and then the value of our metric, which will have a specific format.

[]For example, 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 brand-new users.

[]With measurements, the secret will be ‘name’ followed by the colon once again and the worth of the measurement. For instance, if we wanted to extract the various page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The genuine value remains 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 actually been created from different traffic sources, we can set our metric to be ga: sessions and our dimension to be ga: medium.

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: sessions’], ‘dimensions’: []] ). execute()

Producing A DataFrame

[]The response we obtain from the API remains in the type of a dictionary, with all of the information in key: worth pairs. To make the information simpler to see and evaluate, we can turn it into a Pandas dataframe.

[]To turn our action into a dataframe, we first need to produce 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 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(‘measurements’, [] metricHeaders = columnHeader.get(‘metricHeader’, ). get(‘metricHeaderEntries’, [] rows = report.get(‘information’, ). get(‘rows’, [] for row in rows: dimensions = row.get(‘dimensions’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Including The Action Data

[]When the data remains 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= "" alt="DataFrame Example"/ > More Reaction Demand Examples Multiple Metrics There is also the ability to combine several metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise ask for the API reaction just returns metrics that return specific criteria by adding metric filters. It utilizes the following format:

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

action = service.reports(). batchGet( body= ). perform() []Filters also work for measurements in a similar way, however the filter expressions will be slightly various due to the characteristic nature of dimensions.

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

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


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

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

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

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


[]The API likewise lets you bucket measurements with an integer (numeric) worth into varieties utilizing pie chart containers.

[]For example, bucketing the sessions count measurement into four pails 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= ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has provided you with a standard guide to accessing the Google Analytics API, composing some various demands, and collecting some meaningful insights in an easy-to-view format. I have actually added 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 plans for checking out []the information even more. More resources: Included Image: BestForBest/SMM Panel