How To Access Google Analytics API Via Python

Posted by

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

[]The main Google paperwork discusses that it can be used to:

  • Build customized dashboards to show GA data.
  • Automate complex reporting jobs.
  • Integrate with other applications.

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

[]This post will simply cover a few of the methods that can be used to gain access to various subsets of information utilizing different metrics and measurements.

[]I hope to write a follow-up guide checking out different methods you can analyze, picture, and combine the information.

Setting Up The API

Creating A Google Service Account

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

[]As soon as this has been produced, the next action is to pick 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 Details"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been created, browse to the secret section and include a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a private secret. In this circumstances, choose JSON, and then develop and

wait on 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 actually been produced for the service account– this can be discovered on the primary account page.

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

Enabling The API The last and perhaps crucial action is guaranteeing you have made it possible for access to the API. To do this, ensure you are in the right task 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 needed in order to access the API. If you miss this action, you will be prompted to finish 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 data. I chose Jupyter Notebooks to produce this, however you can also use other incorporated developer

[]environments(IDEs)including PyCharm or VSCode. Installing Libraries The first step is to install the libraries that are required 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 install– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip set up connect! 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. Developing 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 customer tricks JSON download that was generated when producing the private key. This

[]is utilized in a comparable method to an API secret. To easily access this file within your code, ensure 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 Altogether

[]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 added our personal essential file, we can add this to the credentials operate by calling the file and setting it up through the ServiceAccountCredentials action.

[]Then, set up the develop 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 = construct(‘analyticsreporting’, ‘v4’, qualifications=qualifications)

Composing The Request Body

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

[]From the API service build, there is the capability to pick the aspects from the reaction that we want to gain access to. This is called a ReportRequest item and needs the following as a minimum:

  • A legitimate view ID for the viewId field.
  • A minimum of one legitimate entry in the dateRanges field.
  • A minimum of one legitimate entry in the metrics field.

[]View ID

[]As discussed, there are a couple of things that are needed during this develop phase, starting with our viewId. As we have actually already specified formerly, we just require to call that function name (VIEW_ID) rather than adding the whole view ID once again.

[]If you wanted to gather information from a various analytics view in the future, you would simply require to change the ID in the preliminary code block instead of both.

[]Date Variety

[]Then we can add the date range for the dates that we wish to collect the data for. This includes a start date and an end date.

[]There are a number of methods to write this within the construct request.

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

[]Metrics And Measurements

[]The final 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 period, and bounce rate.

[]Measurements are the qualities of users, their sessions, and their actions. For example, page path, traffic source, and keywords utilized.

[]There are a lot of different metrics and measurements that can be accessed. I won’t go through all of them in this post, but they can all be discovered together with additional information and attributes 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 site, landing page, second-page path tracking, and internal search, site speed, and audience metrics.

[]Both the metrics and measurements are added in a dictionary format, utilizing secret: worth pairs. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a specific format.

[]For instance, if we wanted to get a count of all sessions, we would add ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wished to see a count of all brand-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 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 integrating metrics and dimensions to extract the essential insights we are most thinking about.

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

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

Producing A DataFrame

[]The reaction we get from the API remains in the kind of a dictionary, with all of the information in key: worth sets. To make the data much easier to view and examine, we can turn it into a Pandas dataframe.

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

[]Then, calling the action 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 information and include it to our previously empty lists.

dim = [] metric = [] for report in response.get(‘reports’, []: columnHeader = report.get(‘columnHeader’, ) dimensionHeaders = columnHeader.get(‘dimensions’, [] 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, dimensions): dim.append(dimension) for i, values in enumerate(dateRangeValues): for metricHeader, value 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 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 Reaction Demand Examples Multiple 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 likewise ask for the API response only returns metrics that return certain criteria by adding metric filters. It uses the following format:

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

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() []Filters likewise work for measurements in a similar method, but the filter expressions will be a little various due to the characteristic nature of dimensions.

[]For instance, if you just wish to draw out pageviews from users who have gone to the website using the Chrome internet browser, you can set an EXTRACT operator and use ‘Chrome’ as the expression.

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


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

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

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

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


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

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

response = service.reports(). batchGet( body= ). 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, writing some different demands, and collecting some significant insights in an easy-to-view format. I have included the develop and request code, and the snippets shared to this GitHub file. I will like to hear if you attempt any of these and your plans for checking out []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel