How To Gain Access To Google Analytics API Via Python

Posted by

[]The Google Analytics API offers access to Google Analytics (GA) report information such as pageviews, sessions, traffic source, and bounce rate.

[]The official Google documents explains that it can be used to:

  • Construct customized control panels to show GA data.
  • Automate complex reporting jobs.
  • Incorporate with other applications.

[]You can access the API reaction utilizing several various techniques, consisting of Java, PHP, and JavaScript, but this post, in specific, 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 access different subsets of data using different metrics and dimensions.

[]I want to compose a follow-up guide exploring different ways you can analyze, imagine, and integrate the data.

Establishing The API

Creating A Google Service Account

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

[]Once this has actually been produced, the next step is to select 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 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 created, browse to the KEYS section and add a new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a personal secret. In this instance, choose JSON, and then produce and

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

Add To Google Analytics Account

[]You will also want to take a copy of the email that has actually been produced for the service account– this can be found on the main account page.

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

Enabling The API The last and probably crucial action is guaranteeing you have actually made it possible for access to the API. To do this, guarantee you remain in the appropriate job and follow this link to allow gain access to.

[]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 prompted 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 start composing the []script to export the information. I selected Jupyter Notebooks to develop this, but you can also utilize other integrated designer

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

Some are unique to the analytics API, and others work for future areas of the code.! pip install– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import build from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip install functions import connect Note: When using pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t needed. Creating 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 client secrets JSON download that was produced when creating the private secret. This

[]is used in a similar method to an API secret. To easily access this file within your code, guarantee you

[]have actually saved the JSON file in the 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 want 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 function by calling the file and setting it up through the ServiceAccountCredentials step.

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

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

Writing The Demand Body

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

[]From the API service construct, there is the ability to choose the aspects from the action that we want to access. 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 valid entry in the dateRanges field.
  • At least one legitimate entry in the metrics field.

[]View ID

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

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

[]Date Range

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

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

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

[]Metrics And Measurements

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

[]Measurements are the attributes of users, their sessions, and their actions. For instance, page path, 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 post, however they can all be discovered together with additional information and associates here.

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

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

[]For instance, if we wanted 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 new users.

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

[]Integrating Dimensions And Metrics

[]The genuine worth is in combining metrics and dimensions to extract the key insights we are most thinking about.

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

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

Creating A DataFrame

[]The action we get from the API remains in the kind of a dictionary, with all of the information 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 action into a dataframe, we first require to create some empty lists, to hold the metrics and dimensions.

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

[]This will extract the information 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(‘information’, ). get(‘rows’, [] for row in rows: measurements = row.get(‘measurements’, [] 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)) []Including The Action Data

[]As soon as the data remains in those lists, we can easily turn them into a dataframe by specifying the column names, in square brackets, and appointing 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 Several Metrics There is also the capability to integrate numerous metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can also request the API reaction only returns metrics that return certain requirements by adding metric filters. It utilizes the following format:

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

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

[]For instance, if you only want to extract pageviews from users who have visited the website utilizing the Chrome browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out()

Expressions

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

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

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

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

Histograms

[]The API also lets you container measurements with an integer (numerical) value into varieties using pie chart buckets.

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

response = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], “metrics”: [], “dimensions”: [“name”: “ga: sessionCount”, “histogramBuckets”: [” 1″,”10″,”100″,”200″,”400″]], “orderBys”: [“fieldName”: “ga: sessionCount”, “orderType”: “HISTOGRAM_BUCKET”]] ). perform() Screenshot from author, December 2022 In Conclusion I hope this has actually provided you with a fundamental guide to accessing the Google Analytics API, composing some various demands, and collecting some significant insights in an easy-to-view format. I have added the construct and request code, and the snippets shared to this GitHub file. I will love to hear if you attempt any of these and your plans for exploring []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel