How To Access Google Analytics API Via Python

Posted by

[]The Google Analytics API provides 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 used to:

  • Build custom dashboards to show GA information.
  • Automate complex reporting tasks.
  • Integrate with other applications.

[]You can access the API response using several various approaches, including Java, PHP, and JavaScript, however this short article, in specific, will focus on accessing and exporting data using Python.

[]This post will simply cover some of the methods that can be utilized to access different subsets of data using different metrics and measurements.

[]I intend to compose a follow-up guide checking out various methods you can evaluate, imagine, and integrate the information.

Setting Up The API

Creating A Google Service Account

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

[]Once this has been created, the next action is to select the + Produce Service Account button.

Screenshot from Google Cloud, December 2022 You will then be promoted to include some details 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 produced, browse to the secret section and add a new key. Screenshot from Google Cloud, December 2022 [] This will trigger you to create and download a private key. In this circumstances, select JSON, and after that develop and

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

Add 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 found 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 authorizations. Screenshot from Google Analytics, December 2022

Making it possible for The API The last and probably crucial action is guaranteeing you have actually made it possible for access to the API. To do this, ensure you remain in the proper job and follow this link to enable access.

[]Then, follow the actions to enable 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 triggered to complete it when very first running the script. Accessing The Google Analytics API With Python Now whatever is established in our service account, we can start writing the []script to export the information. I picked Jupyter Notebooks to create this, however you can likewise use other incorporated designer

[]environments(IDEs)including PyCharm or VSCode. Installing Libraries The primary step is to install the libraries that are needed to run the rest of the code.

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

[]is used in a comparable way to an API key. To quickly access this file within your code, ensure you

[]have conserved 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, add the view ID from the analytics account with which you want to access the data. Screenshot from author, December 2022 Completely

[]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 added our private crucial file, we can add this to the qualifications work 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 specified qualifications from above.

qualifications = 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 set up and specified, the genuine enjoyable begins.

[]From the API service develop, there is the capability to pick the components from the reaction that we want to access. This is called a ReportRequest object 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 mentioned, there are a few things that are required throughout this construct phase, starting with our viewId. As we have actually currently defined previously, we simply require to call that function name (VIEW_ID) rather than including the whole view ID again.

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

[]Date Variety

[]Then we can include the date range for the dates that we want to collect 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 specified dates, for example, between 2 dates, by including 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 30 days, you can set the start date as ’30daysAgo’ and the end date as ‘today.’

[]Metrics And Dimensions

[]The final action of the standard 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 characteristics of users, their sessions, and their actions. For example, page path, traffic source, and keywords used.

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

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

[]Both the metrics and dimensions are included a dictionary format, utilizing secret: worth sets. For metrics, the key will be ‘expression’ followed by the colon (:-RRB- and then the worth of our metric, which will have a specific 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 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 wished to draw out the various page paths, it would be ‘name’: ‘ga: pagePath’.

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

[]Combining Dimensions And Metrics

[]The genuine worth remains in integrating metrics and measurements to extract the essential insights we are most interested in.

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

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

Developing A DataFrame

[]The action we obtain from the API remains in the type of a dictionary, with all of the data in secret: value sets. To make the information simpler to view and evaluate, we can turn it into a Pandas dataframe.

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

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

[]This will extract the information and add it to our formerly 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, dimension in zip(dimensionHeaders, dimensions): dim.append(measurement) for i, worths in enumerate(dateRangeValues): for metricHeader, value 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 specifying the column names, in square brackets, and designating 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 Request Examples Numerous Metrics There is also the capability to combine multiple metrics, with each pair included curly brackets and separated by a comma. ‘metrics’: [“expression”: “ga: pageviews”, ] Filtering []You can also request the API action just returns metrics that return specific requirements by including metric filters. It uses the following format:

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

action = service.reports(). batchGet( body= ‘reportRequests’: [] ). carry out() []Filters likewise work for measurements in a comparable method, however the filter expressions will be slightly different due to the particular nature of measurements.

[]For example, if you just want to extract pageviews from users who have checked out the website using the Chrome browser, you can set an EXTRACT operator and usage ‘Chrome’ as the expression.

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


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

[]This involves defining an alias to represent the expression and finishing a mathematical function on two metrics.

[]For instance, you can calculate completions per user by dividing the variety of conclusions by the variety of users.

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


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

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

reaction = service.reports(). batchGet( body= ‘reportRequests’: [‘viewId’: VIEW_ID, ‘dateRanges’: [], “metrics”: [“expression”: “ga: sessions”], “measurements”: [], “orderBys”: []] ). carry out() Screenshot from author, December 2022 In Conclusion I hope this has actually offered you with a standard guide to accessing the Google Analytics API, writing some various demands, and collecting some significant insights in an easy-to-view format. I have actually included the develop and request code, and the snippets shared to this GitHub file. I will like to hear if you try any of these and your plans for exploring []the information even more. More resources: Included Image: BestForBest/Best SMM Panel