How To Gain Access To Google Analytics API Via Python

Posted by

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

[]The official Google paperwork discusses that it can be utilized to:

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

[]You can access the API reaction using a number of different methods, including Java, PHP, and JavaScript, but this post, in particular, will concentrate on accessing and exporting information using Python.

[]This short article will simply cover a few of the techniques that can be used to gain access to various subsets of information utilizing various metrics and dimensions.

[]I hope to compose a follow-up guide exploring various methods you can examine, picture, and integrate the information.

Setting Up The API

Developing A Google Service Account

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

[]As soon as this has actually been produced, the next step is to pick the + Create 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= "// www.w3.org/2000/svg%22%20viewBox=%220%200%201152%201124%22%3E%3C/svg%3E"alt="Service Account Particulars"width="1152"height=" 1124"data-src="https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-12-at-20.20.21-639b81474320f-sej.png"/ > Screenshot from Google Cloud, December 2022 Once the service account has actually been developed, browse to the KEYS section and add a new secret. Screenshot from Google Cloud, December 2022 [] This will prompt you to create and download a personal key. In this instance, choose JSON, and then develop 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 been generated 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 email []as a user in Google Analytics with Analyst approvals. Screenshot from Google Analytics, December 2022

Allowing The API The last and arguably crucial step is guaranteeing you have actually made it possible for access to the API. To do this, ensure you remain in the appropriate 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 triggered to complete it when 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 information. I selected Jupyter Notebooks to produce this, but you can likewise utilize other incorporated designer

[]environments(IDEs)consisting of PyCharm or VSCode. Installing 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 areas of the code.! pip install– upgrade google-api-python-client! pip3 install– upgrade oauth2client from apiclient.discovery import develop from oauth2client.service _ account import ServiceAccountCredentials! pip install connect! pip install functions import connect Note: When using pip in a Jupyter notebook, include the!– if running in the command line or another IDE, the! isn’t needed. Creating 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 customer tricks JSON download that was generated when producing the personal secret. This

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

[]have saved the JSON file in the very 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 wish to access the information. Screenshot from author, December 2022 Altogether

[]this will look like the following. We will reference these functions throughout our code.

SCOPES = [‘ https://www.googleapis.com/auth/analytics.readonly’] KEY_FILE_LOCATION=’client_secrets. json’ VIEW_ID=’XXXXX’ []Once we have actually included our personal crucial file, we can include this to the qualifications work by calling the file and setting it up through the ServiceAccountCredentials step.

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

credentials = 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 defined, the real enjoyable begins.

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

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

[]View ID

[]As discussed, there are a few things that are required during this build stage, starting with our viewId. As we have currently specified previously, we simply need to call that function name (VIEW_ID) instead of including the whole view ID once again.

[]If you wanted to gather information from a various analytics view in the future, you would just need to alter the ID in the initial code block rather than both.

[]Date Variety

[]Then we can add the date range for the dates that we want to gather the information for. This consists of a start date and an end date.

[]There are a couple of methods to write this within the develop demand.

[]You can select defined dates, for instance, 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 data from the last 30 days, you can set the start date as ’30daysAgo’ and completion date as ‘today.’

[]Metrics And Dimensions

[]The last step of the basic response call is setting the metrics and dimensions. 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 used.

[]There are a lot of various metrics and measurements that can be accessed. I will not go through all of them in this article, however they can all be found together with extra details and attributes here.

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

[]Both the metrics and measurements are included a dictionary format, utilizing key: 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 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 brand-new users.

[]With measurements, the secret will be ‘name’ followed by the colon again and the value of the dimension. For instance, if we wished 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 website.

[]Integrating Dimensions And Metrics

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

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

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

Developing A DataFrame

[]The action we receive from the API is in the kind of a dictionary, with all of the data in secret: worth sets. To make the data simpler to view and analyze, we can turn it into a Pandas dataframe.

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

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

[]Once the information is in those lists, we can easily turn them into a dataframe by defining 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= "https://cdn.searchenginejournal.com/wp-content/uploads/2022/12/screenshot-2022-12-13-at-20.30.15-639b817e87a2c-sej.png" alt="DataFrame Example"/ > More Response Demand Examples Numerous Metrics There is also the capability to combine several metrics, with each set included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, “expression”: “ga: sessions”] Filtering []You can also request the API action only returns metrics that return certain criteria by including metric filters. It uses the following format:

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [] ). perform() []Filters also work for dimensions in a comparable method, however the filter expressions will be a little different due to the particular nature of measurements.

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [‘expression’: ‘ga: pageviews’], “measurements”: [“name”: “ga: web browser”], “dimensionFilterClauses”: [“filters”: [“dimensionName”: “ga: web browser”, “operator”: “EXACT”, “expressions”: [” Chrome”]]]] ). execute()

Expressions

[]As metrics are quantitative measures, there is likewise the ability to compose expressions, which work likewise to determined metrics.

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

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

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

Histograms

[]The API likewise lets you container dimensions with an integer (numerical) worth into ranges utilizing histogram containers.

[]For example, bucketing the sessions count measurement 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= ). execute() Screenshot from author, December 2022 In Conclusion I hope this has supplied you with a fundamental guide to accessing the Google Analytics API, composing some different demands, and collecting some meaningful insights in an easy-to-view format. I have actually added the develop and ask for code, and the bits shared to this GitHub file. I will enjoy to hear if you attempt any of these and your prepare for checking out []the data even more. More resources: Featured Image: BestForBest/Best SMM Panel