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

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

[]You can access the API action using numerous various techniques, including Java, PHP, and JavaScript, however this short article, in specific, will concentrate on accessing and exporting data utilizing Python.

[]This post will simply cover some of the approaches that can be utilized to access different subsets of data using various metrics and measurements.

[]I want to write a follow-up guide checking out various ways you can examine, picture, and integrate the data.

Establishing The API

Developing A Google Service Account

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

[]Once this has been developed, the next action is to pick the + Produce Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to add some information 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, browse to the KEYS area and include a new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to develop and download a personal secret. In this circumstances, choose JSON, and then create and

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

Add To Google Analytics Account

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

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

Enabling The API The last and arguably essential action is guaranteeing you have actually made it possible for access to the API. To do this, guarantee you are in the proper job and follow this link to enable gain access to.

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

Screenshot from Google Cloud, December 2022 This is required in order to access the API. If you miss this action, you will be prompted to complete it when first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can begin composing the []script to export the data. I picked Jupyter Notebooks to develop this, but you can also use other integrated developer

[]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 special to the analytics API, and others are useful for future sections of the code.! pip set up– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import build from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip install functions import connect Note: When utilizing pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t required. 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 client secrets JSON download that was generated when producing the private secret. This

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

[]have conserved the JSON file in the 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 want to access the information. Screenshot from author, December 2022 Entirely

[]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 personal crucial file, we can add this to the credentials 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 currently defined qualifications from above.

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

Writing The Demand Body

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

[]From the API service build, there is the capability to select the elements from the response that we wish to access. This is called a ReportRequest things and needs 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 required during this construct phase, starting with our viewId. As we have currently specified previously, we simply need to call that function name (VIEW_ID) instead of adding the whole view ID again.

[]If you wished to collect 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 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 write this within the construct request.

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

[]Metrics And Measurements

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

[]Dimensions are the qualities of users, their sessions, and their actions. For instance, page course, 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 article, but they can all be found together with extra info and attributes here.

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

[]Both the metrics and dimensions are added in a dictionary format, utilizing secret: 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 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 wished to see a count of all new users.

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

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

[]Integrating Measurements And Metrics

[]The genuine value remains in combining metrics and measurements to draw out the crucial insights we are most thinking about.

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

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

Developing A DataFrame

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

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

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

[]Once the data remains in those lists, we can quickly turn them into a dataframe by defining 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 Response Demand Examples Multiple Metrics There is also the capability to combine numerous metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering []You can also ask for the API reaction only returns metrics that return certain criteria by including metric filters. It utilizes the following format:

if return the metric []For instance, if you only wanted to draw out pageviews with more than ten views.

response = service.reports(). batchGet( body= ). execute() []Filters likewise work for measurements in a comparable method, but the filter expressions will be somewhat different due to the particular nature of measurements.

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

action = service.reports(). batchGet( body= ). perform()


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

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

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

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


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

[]For example, bucketing the sessions count dimension into 4 pails 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 supplied you with a standard guide to accessing the Google Analytics API, writing some various demands, and gathering some meaningful insights in an easy-to-view format. I have included the build and ask for 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 further. More resources: Featured Image: BestForBest/SMM Panel

Leave a Reply

Your email address will not be published. Required fields are marked *