How To Gain Access To 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 describes that it can be utilized to:

  • Develop custom dashboards to show GA data.
  • Automate complex reporting jobs.
  • Integrate with other applications.

[]You can access the API action using a number of various approaches, including Java, PHP, and JavaScript, however this article, in particular, will concentrate on accessing and exporting information utilizing Python.

[]This short article will just cover a few of the approaches that can be used to gain access to different subsets of data utilizing different metrics and dimensions.

[]I wish to compose a follow-up guide checking out various ways you can evaluate, imagine, and integrate the information.

Setting Up The API

Creating A Google Service Account

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

[]When this has actually been produced, the next step is to pick the + Create 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 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 produced, browse to the secret section and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to produce and download a private secret. In this circumstances, select JSON, and after that develop and

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

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

Enabling The API The last and arguably most important step is ensuring you have actually made it possible for access to the API. To do this, ensure you are in the right job and follow this link to enable access.

[]Then, follow the actions to allow 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 triggered to finish it when first running the script. Accessing The Google Analytics API With Python Now whatever is set up in our service account, we can start writing the []script to export the information. I picked Jupyter Notebooks to create this, however you can likewise utilize other integrated developer

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

Some are distinct 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 link! pip install functions import link Note: When using pip in a Jupyter note pad, include the!– if running in the command line or another IDE, the! isn’t needed. Producing A Service Build The next action is to set []up our scope, which is the read-only analytics API authentication link. This is followed by the client tricks JSON download that was generated when developing the private key. This

[]is used in a similar way to an API key. To quickly access this file within your code, ensure you

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

[]Finally, add 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 = [‘ https://www.googleapis.com/auth/analytics.readonly’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have actually added our personal essential file, we can add this to the qualifications operate 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.

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

Writing The Request Body

[]When we have everything established and defined, the real enjoyable starts.

[]From the API service construct, there is the ability to pick the aspects from the reaction that we want to gain access to. This is called a ReportRequest things 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 legitimate entry in the metrics field.

[]View ID

[]As pointed out, there are a couple of things that are required throughout this construct phase, starting with our viewId. As we have actually currently defined previously, we simply require to call that function name (VIEW_ID) instead of including the whole view ID once again.

[]If you wanted to collect data from a different analytics see in the future, you would just require to change the ID in the preliminary code block instead of both.

[]Date Range

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

[]There are a number of ways to compose this within the construct demand.

[]You can choose specified dates, for example, in between two dates, by including 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 thirty days, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The final step of the fundamental reaction call is setting the metrics and dimensions. Metrics are the quantitative measurements from Google Analytics, such as session count, session duration, and bounce rate.

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

[]There are a lot of various metrics and measurements 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 associates here.

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

[]Both the metrics and dimensions are included a dictionary format, utilizing key: value pairs. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the value 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 wanted to see a count of all brand-new users.

[]With dimensions, the key will be ‘name’ followed by the colon again and the worth of the measurement. For example, if we wanted to draw out the different page courses, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The genuine value is in combining metrics and measurements to draw out the essential 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 measurement to be ga: medium.

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). execute()

Producing A DataFrame

[]The action we receive from the API remains in the kind of a dictionary, with all of the information in secret: worth sets. To make the data easier to view and analyze, we can turn it into a Pandas dataframe.

[]To turn our action into a dataframe, we initially need to create some empty lists, to hold the metrics and dimensions.

[]Then, calling the action output, we will add the data from the measurements into the empty dimensions list and a count of the metrics into the metrics list.

[]This will draw out the information and include 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: dimensions = row.get(‘dimensions’, [] dateRangeValues = row.get(‘metrics’, [] for header, measurement in zip(dimensionHeaders, measurements): dim.append(dimension) for i, values in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘values’)): metric.append(int(value)) []Adding The Response 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 designating 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 Action Request Examples Numerous Metrics There is likewise the capability to combine several metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can likewise request the API response only returns metrics that return certain requirements by adding metric filters. It utilizes the following format:

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

reaction = service.reports(). batchGet( body= ). perform() []Filters also work for dimensions in a similar method, but the filter expressions will be somewhat different due to the particular nature of measurements.

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: pageviews’], “dimensions”: [], “dimensionFilterClauses”: [“filters”: []]] ). carry out()

Expressions

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

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

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [ga: users”, “alias”: “conclusions per user”]] ). perform()

Histograms

[]The API also lets you bucket dimensions with an integer (numerical) value into varieties using pie chart containers.

[]For instance, bucketing the sessions count dimension 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.

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually offered you with a fundamental 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 included the develop and request code, and the bits shared to this GitHub file. I will enjoy to hear if you attempt any of these and your prepare for checking out []the information further. More resources: Included Image: BestForBest/Best SMM Panel