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 documentation describes that it can be utilized to:

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

[]You can access the API action utilizing a number of various approaches, consisting of Java, PHP, and JavaScript, but this short article, in particular, will focus on accessing and exporting data using Python.

[]This post will simply cover a few of the techniques that can be utilized to gain access to different subsets of data using different metrics and measurements.

[]I want to write a follow-up guide exploring various methods you can analyze, picture, and combine the data.

Setting Up The API

Producing A Google Service Account

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

[]When this has actually been developed, 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 information such as a name, ID, and description.< img src= "//"alt="Service Account Particulars"width="1152"height=" 1124"data-src=""/ > Screenshot from Google Cloud, December 2022 Once the service account has been created, browse to the KEYS section and include a new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to produce and download a private secret. In this circumstances, choose JSON, and after that create and

await 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 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 e-mail []as a user in Google Analytics with Expert consents. Screenshot from Google Analytics, December 2022

Enabling The API The last and perhaps crucial action is guaranteeing you have allowed access to the API. To do this, ensure you remain in the right job and follow this link to allow 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 step, you will be triggered 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 writing the []script to export the data. I selected Jupyter Notebooks to produce this, but you can also utilize other integrated developer

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

Some are unique to the analytics API, and others work for future areas of the code.! pip set up– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import construct from oauth2client.service _ account import ServiceAccountCredentials! pip install link! pip install functions import link Note: When utilizing pip in a Jupyter notebook, add the!– if running in the command line or another IDE, the! isn’t needed. Developing A Service Develop 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 developing the private secret. This

[]is used in a comparable way to an API key. 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 key file, we can include this to the qualifications work by calling the file and setting it up through the ServiceAccountCredentials step.

[]Then, established the construct report, calling the analytics reporting API V4, and our already specified qualifications from above.

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

Writing The Demand Body

[]As soon as we have whatever established and specified, the genuine fun starts.

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

  • A valid 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 required during this develop phase, starting with our viewId. As we have currently defined formerly, we simply need to call that function name (VIEW_ID) rather than including the entire view ID once again.

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

[]Date Variety

[]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 couple of ways to compose this within the develop demand.

[]You can choose defined dates, for instance, between 2 dates, by adding 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 Dimensions

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

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

[]There are a lot of various metrics and dimensions that can be accessed. I won’t go through all of them in this short article, but they can all be found together with additional info and attributes here.

[]Anything you can access in Google Analytics you can access in the API. This consists of goal conversions, starts and values, the browser device utilized 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 key: value sets. For metrics, the secret will be ‘expression’ followed by the colon (:-RRB- and then the worth 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 new users.

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

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

[]Integrating Dimensions And Metrics

[]The genuine value is in combining metrics and dimensions to extract the key insights we are most interested in.

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

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

Creating A DataFrame

[]The reaction we get from the API remains in the type of a dictionary, with all of the information in secret: value pairs. To make the data much easier to view and analyze, 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 information from the measurements into the empty measurements list and a count of the metrics into the metrics list.

[]This will extract the data and include it to our formerly 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: measurements = row.get(‘measurements’, [] dateRangeValues = row.get(‘metrics’, [] for header, dimension in zip(dimensionHeaders, measurements): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, worth in zip(metricHeaders, values.get(‘values’)): metric.append(int(worth)) []Including The Action Data

[]When the data is in those lists, we can easily turn them into a dataframe by specifying the column names, in square brackets, and appointing the list worths 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 likewise the ability to combine numerous metrics, with each set added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can likewise ask for the API reaction just returns metrics that return particular requirements by including metric filters. It uses the following format:

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

response = service.reports(). batchGet( body= ). carry out() []Filters also work for measurements in a comparable method, however the filter expressions will be a little various due to the particular nature of dimensions.

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

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


[]As metrics are quantitative steps, there is likewise the capability to write expressions, which work similarly to calculated metrics.

[]This includes defining 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.

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [‘startDate’: ’30daysAgo’, ‘endDate’: ‘today’], “metrics”: [“expression”: “ga: goal1completions]] ). perform()


[]The API likewise lets you pail dimensions with an integer (numerical) value into varieties using histogram buckets.

[]For example, 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= ). perform() Screenshot from author, December 2022 In Conclusion I hope this has offered you with a basic guide to accessing the Google Analytics API, writing some various demands, and gathering some significant 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 love to hear if you attempt any of these and your plans for exploring []the data further. More resources: Included Image: BestForBest/Best SMM Panel