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

  • Construct customized dashboards to show GA information.
  • Automate complex reporting jobs.
  • Integrate with other applications.

[]You can access the API response using numerous various methods, consisting of Java, PHP, and JavaScript, but this short article, in particular, will concentrate on accessing and exporting information using Python.

[]This short article will just cover some of the methods that can be utilized to gain access to various subsets of data using various metrics and measurements.

[]I hope to write a follow-up guide checking out various ways you can analyze, envision, and combine the data.

Setting Up The API

Producing A Google Service Account

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

[]When this has actually been developed, the next action is to pick 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= "//"alt="Service Account Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been developed, navigate to the secret area and add a new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to produce and download a private secret. In this circumstances, select JSON, and then produce and

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

Add To Google Analytics Account

[]You will likewise want to take a copy of the email that has actually 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 add that e-mail []as a user in Google Analytics with Analyst consents. Screenshot from Google Analytics, December 2022

Enabling The API The last and probably crucial step is guaranteeing you have made it possible for access to the API. To do this, ensure you are in the correct task and follow this link to make it possible for access.

[]Then, follow the actions 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 prompted to finish it when very first running the script. Accessing The Google Analytics API With Python Now whatever is set up in our service account, we can begin writing the []script to export the data. I selected Jupyter Notebooks to create this, however you can likewise use other incorporated developer

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

Some are unique 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 develop from oauth2client.service _ account import ServiceAccountCredentials! pip set up link! pip set up 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. Creating 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 customer tricks JSON download that was produced when developing the personal key. This

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

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

[]Finally, include the view ID from the analytics account with which you wish to access the information. Screenshot from author, December 2022 Completely

[]this will appear 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 private essential file, we can add this to the qualifications work by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, set up the build report, calling the analytics reporting API V4, and our already defined qualifications from above.

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

Writing The Request Body

[]As soon as we have whatever established and specified, the genuine enjoyable begins.

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

  • A valid 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 discussed, there are a few things that are needed during this construct stage, beginning with our viewId. As we have currently defined previously, we simply require to call that function name (VIEW_ID) instead of including the entire view ID again.

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

[]Date Variety

[]Then we can add the date range for the dates that we want to gather the information 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 select specified dates, for instance, 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 one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Measurements

[]The final action of the basic 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 qualities of users, their sessions, and their actions. For instance, page path, traffic source, and keywords utilized.

[]There are a lot of various metrics and measurements that can be accessed. I won’t go through all of them in this short article, but they can all be found together with extra 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 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, 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 example, 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 brand-new users.

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

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

[]Integrating Dimensions And Metrics

[]The genuine worth is in combining metrics and measurements to draw out the key insights we are most interested in.

[]For example, to see a count of all sessions that have been produced 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 reaction we receive from the API remains in the kind of a dictionary, with all of the data in key: worth sets. To make the information simpler to view and examine, we can turn it into a Pandas dataframe.

[]To turn our reaction into a dataframe, we first need to create some empty lists, to hold the metrics and measurements.

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

[]This will extract 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(‘information’, ). get(‘rows’, [] for row in rows: measurements = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(dimension) for i, worths in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get(‘worths’)): metric.append(int(value)) []Adding The Action Data

[]As soon as the information is 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= "" alt="DataFrame Example"/ > More Action Demand Examples Numerous Metrics There is also the ability to combine several metrics, with each pair added in curly brackets and separated by a comma. ‘metrics’: [, “expression”: “ga: sessions”] Filtering []You can likewise ask for the API action just returns metrics that return certain criteria by adding metric filters. It uses the following format:

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], ‘metrics’: [‘expression’: ‘ga: pageviews’], ‘measurements’: [], “metricFilterClauses”: []] ). perform() []Filters likewise work for measurements in a similar way, but the filter expressions will be slightly different due to the characteristic nature of dimensions.

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

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


[]As metrics are quantitative steps, there is likewise 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 instance, you can compute conclusions per user by dividing the number of conclusions by the number of users.

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


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

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], “metrics”: [], “measurements”: [], “orderBys”: [“fieldName”: “ga: sessionCount”, “orderType”: “HISTOGRAM_BUCKET”]] ). execute() Screenshot from author, December 2022 In Conclusion I hope this has supplied you with a basic guide to accessing the Google Analytics API, composing some various requests, and gathering some meaningful insights in an easy-to-view format. I have included the build and ask for code, and the bits shared to this GitHub file. I will like to hear if you attempt any of these and your prepare for checking out []the information further. More resources: Included Image: BestForBest/SMM Panel