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

  • Construct custom-made control panels to show GA information.
  • Automate complex reporting jobs.
  • Integrate with other applications.

[]You can access the API response utilizing several different approaches, including Java, PHP, and JavaScript, however this post, in specific, will concentrate on accessing and exporting data using Python.

[]This post will just cover some of the methods that can be utilized to gain access to various subsets of information using various metrics and measurements.

[]I hope to compose a follow-up guide checking out various methods you can evaluate, visualize, and combine the information.

Establishing The API

Producing A Google Service Account

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

[]As soon as this has actually been created, the next step is to pick the + Produce 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 actually been produced, browse to the secret area and include a brand-new key. Screenshot from Google Cloud, December 2022 [] This will prompt you to develop and download a private secret. In this circumstances, select JSON, and then create and

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

Add To Google Analytics Account

[]You will also want to take a copy of the email that has been created for the service account– this can be discovered on the main account page.

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

Making it possible for The API The final and arguably essential step is guaranteeing you have made it possible for access to the API. To do this, guarantee you are in the proper project and follow this link to make it possible for access.

[]Then, follow the actions to enable 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 triggered to finish it when first running the script. Accessing The Google Analytics API With Python Now everything is set up in our service account, we can begin composing the []script to export the data. I selected Jupyter Notebooks to produce this, however you can also utilize other integrated developer

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

Some are distinct to the analytics API, and others work for future sections of the code.! pip install– upgrade google-api-python-client! pip3 set up– upgrade oauth2client from apiclient.discovery import build from oauth2client.service _ account import ServiceAccountCredentials! pip set up connect! pip install functions import link Note: When utilizing pip in a Jupyter note pad, include the!– if running in the command line or another IDE, the! isn’t required. Producing 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 produced when producing the private key. This

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

[]have 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.

[]Finally, add the view ID from the analytics account with which you want to access the data. Screenshot from author, December 2022 Completely

[]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 key file, we can include this to the credentials function 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.

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

Composing The Request Body

[]Once we have everything set up and defined, the genuine enjoyable starts.

[]From the API service build, there is the capability to select the components from the action that we want to gain access to. 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 throughout this build phase, beginning with our viewId. As we have currently specified formerly, we simply need to call that function name (VIEW_ID) rather than adding the whole view ID again.

[]If you wanted to gather data from a various analytics see in the future, you would simply require to change the ID in the initial code block rather than both.

[]Date Range

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

[]There are a number of methods to compose this within the construct demand.

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

[]Or, if you want to see information from the last one month, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

[]The last step of the basic reaction call is setting the metrics and measurements. Metrics are the quantitative measurements from Google Analytics, such as session count, session duration, and bounce rate.

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

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

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

[]Both the metrics and dimensions are added in a dictionary format, using key: worth 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 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 dimensions, the key will be ‘name’ followed by the colon once again and the worth of the measurement. For instance, if we wanted to extract the different page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Measurements And Metrics

[]The real value is in combining metrics and dimensions to draw out the crucial insights we are most interested in.

[]For example, to see a count of all sessions that have been developed 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= ). execute()

Creating A DataFrame

[]The response we get from the API is in the type of a dictionary, with all of the data in secret: worth sets. To make the data easier to view and examine, we can turn it into a Pandas dataframe.

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

[]Then, calling the reaction output, we will add the information from the dimensions into the empty measurements 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(‘measurements’, [] 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, dimension 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(worth)) []Including The Response Data

[]When the data is in those lists, we can quickly 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 Action Demand Examples Numerous Metrics There is likewise the capability to combine multiple metrics, with each set added in curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering []You can also ask for the API reaction just returns metrics that return certain requirements by including metric filters. It utilizes the following format:

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

action = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], ‘metrics’: [], ‘dimensions’: [‘name’: ‘ga: pagePath’], “metricFilterClauses”: [“filters”: []]] ). carry out() []Filters likewise work for measurements in a similar way, however the filter expressions will be a little different due to the characteristic nature of dimensions.

[]For instance, if you just want to draw out pageviews from users who have actually visited the site using the Chrome internet browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

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


[]As metrics are quantitative steps, there is also the capability to compose expressions, which work similarly to determined metrics.

[]This includes specifying 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 conclusions by the number of users.

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


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

[]For instance, 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 define the ranges in histogramBuckets.

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually supplied you with a standard guide to accessing the Google Analytics API, composing some various requests, and collecting some significant insights in an easy-to-view format. I have actually included the develop and ask for code, and the bits shared to this GitHub file. I will like to hear if you try any of these and your plans for exploring []the data further. More resources: Featured Image: BestForBest/Best SMM Panel