How To Gain Access To Google Analytics API Via Python

Posted by

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

[]The official Google documentation explains that it can be utilized to:

  • Build customized control panels to display GA information.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API reaction using a number of different approaches, including Java, PHP, and JavaScript, however this short article, in specific, will concentrate on accessing and exporting information using Python.

[]This article will just cover a few of the methods that can be used to access different subsets of data utilizing different metrics and measurements.

[]I wish to write a follow-up guide checking out various ways you can evaluate, envision, and integrate the information.

Setting Up The API

Developing A Google Service Account

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

[]As soon as this has been created, the next action is to choose 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 developed, browse to the secret area and add a brand-new secret. Screenshot from Google Cloud, December 2022 [] This will trigger you to develop and download a private secret. In this instance, select JSON, and then develop and

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

Contribute To Google Analytics Account

[]You will likewise wish to take a copy of the email that has actually been produced for the service account– this can be discovered on the main 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 permissions. Screenshot from Google Analytics, December 2022

Enabling The API The last and perhaps essential step is ensuring 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 enable access.

[]Then, follow the actions 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 finish it when 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 picked Jupyter Notebooks to create this, but you can likewise utilize other integrated designer

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

Some are distinct 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 connect! 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 required. Producing A Service Construct 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 produced when developing the private secret. This

[]is utilized in a similar method to an API secret. To quickly access this file within your code, ensure you

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

[]Lastly, include the view ID from the analytics account with which you wish 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 = [‘’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have included our private essential file, we can add this to the credentials work 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 specified qualifications from above.

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

Composing The Demand Body

[]As soon as we have whatever established and defined, the real fun begins.

[]From the API service build, there is the ability to select the components from the action that we want to access. This is called a ReportRequest item and requires 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 valid entry in the metrics field.

[]View ID

[]As pointed out, there are a few things that are needed throughout this construct stage, starting with our viewId. As we have already defined formerly, we just need to call that function name (VIEW_ID) rather than adding the whole view ID again.

[]If you wished to collect information from a different analytics view in the future, you would just need to alter the ID in the preliminary code block rather than both.

[]Date Variety

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

[]There are a number of ways to compose this within the build demand.

[]You can pick defined dates, for example, in between two dates, by adding the date in a year-month-date format, ‘startDate’: ‘2022-10-27’, ‘endDate’: ‘2022-11-27’.

[]Or, if you wish to see information from the last 30 days, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]The final step of the fundamental 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 course, 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 article, but they can all be found together with additional info and associates here.

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

[]Both the metrics and dimensions are added in a dictionary format, utilizing secret: value sets. For metrics, the secret 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 add ‘expression’: ‘ga: sessions’. Or ‘expression’: ‘ga: newUsers’ if we wanted 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 example, if we wished to draw out the different 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 real value remains in combining metrics and dimensions to draw out the crucial insights we are most thinking about.

[]For instance, to see a count of all sessions that have actually been created from various 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’: [], ‘metrics’: [], ‘measurements’: []] ). carry out()

Producing A DataFrame

[]The reaction we obtain from the API is in the form of a dictionary, with all of the information in key: worth sets. To make the data simpler to view and analyze, we can turn it into a Pandas dataframe.

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

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

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

[]When the information is 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 Request Examples Several Metrics There is likewise the ability to combine multiple metrics, with each set added in curly brackets and separated by a comma. ‘metrics’: [, ] Filtering []You can also request the API action just returns metrics that return particular criteria by adding metric filters. It utilizes the following format:

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

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

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

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


[]As metrics are quantitative steps, there is also the capability to compose 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 example, you can compute completions per user by dividing the number of conclusions by the variety of users.

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


[]The API likewise lets you pail measurements with an integer (numerical) worth into ranges using pie chart containers.

[]For example, bucketing the sessions count measurement into four buckets of 1-9, 10-99, 100-199, and 200-399, you can utilize the HISTOGRAM_BUCKET order type and specify the ranges in histogramBuckets.

response = service.reports(). batchGet( body= ‘reportRequests’: [] ). execute() Screenshot from author, December 2022 In Conclusion I hope this has actually supplied you with a basic guide to accessing the Google Analytics API, composing some various requests, and collecting some meaningful insights in an easy-to-view format. I have actually included the construct and request code, and the bits shared to this GitHub file. I will love to hear if you attempt any of these and your prepare for exploring []the information even more. More resources: Featured Image: BestForBest/Best SMM Panel