The Google Analytics API gives entry to Google Analytics (GA) report knowledge similar to pageviews, periods, visitors supply, and bounce price.
The official Google documentation explains that it may be used to:
- Construct customized dashboards to show GA knowledge.
- Automate advanced reporting duties.
- Combine with different purposes.
You possibly can entry the API response utilizing a number of totally different strategies, together with Java, PHP, and JavaScript, however this text, particularly, will concentrate on accessing and exporting knowledge utilizing Python.
This text will simply cowl among the strategies that can be utilized to entry totally different subsets of knowledge utilizing totally different metrics and dimensions.
I hope to put in writing a follow-up information exploring other ways you possibly can analyze, visualize, and mix the information.
Setting Up The API
Creating A Google Service Account
Step one is to create a mission or choose one inside your Google Service Account.
As soon as this has been created, the subsequent step is to pick out the + Create Service Account button.
You’ll then be promoted so as to add some particulars similar to a reputation, ID, and outline.

As soon as the service account has been created, navigate to the KEYS part and add a brand new key.

It will immediate you to create and obtain a non-public key. On this occasion, choose JSON, after which create and look ahead to the file to obtain.

Add To Google Analytics Account
Additionally, you will need to take a replica of the e-mail that has been generated for the service account – this may be discovered on the primary account web page.

The subsequent step is so as to add that e mail as a person in Google Analytics with Analyst permissions.

Enabling The API
The ultimate and arguably most essential step is making certain you may have enabled entry to the API. To do that, guarantee you’re within the right mission and observe this link to enable access.
Then, observe the steps to allow it when promoted.

That is wanted with a view to entry the API. When you miss this step, you may be prompted to finish it when first working the script.
Accessing The Google Analytics API With Python
Now the whole lot is ready up in our service account, we will begin writing the script to export the information.
I selected Jupyter Notebooks to create this, however it’s also possible to use different built-in developer environments (IDEs) together with PyCharm or VSCode.
Putting in Libraries
Step one is to put in the libraries which can be wanted to run the remainder of the code.
Some are distinctive to the analytics API, and others are helpful for future sections of the code.
!pip set up --upgrade google-api-python-client !pip3 set up --upgrade oauth2client from apiclient.discovery import construct from oauth2client.service_account import ServiceAccountCredentials !pip set up join !pip set up capabilities import join
Be aware: When utilizing pip in a Jupyter pocket book, add the ! – if working within the command line or one other IDE, the ! isn’t wanted.
Creating A Service Construct
The subsequent step is to arrange our scope, which is the read-only analytics API authentication hyperlink.
That is adopted by the shopper secrets and techniques JSON obtain that was generated when creating the non-public key. That is utilized in an identical approach to an API key.
To simply entry this file inside your code, guarantee you may have saved the JSON file in the identical folder because the code file. This may then simply be referred to as with the KEY_FILE_LOCATION operate.
Lastly, add the view ID from the analytics account with which you wish to entry the information.

Altogether this may seem like the next. We’ll reference these capabilities all through our code.
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'client_secrets.json' VIEW_ID = 'XXXXX'
As soon as we have now added our non-public key file, we will add this to the credentials operate by calling the file and setting it up by the ServiceAccountCredentials step.
Then, arrange the construct report, calling the analytics reporting API V4, and our already outlined credentials from above.
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES) service = construct('analyticsreporting', 'v4', credentials=credentials)
Writing The Request Physique
As soon as we have now the whole lot arrange and outlined, the true enjoyable begins.
From the API service construct, there’s the flexibility to pick out the weather from the response that we need to entry. That is referred to as a ReportRequest object and requires the next at least:
- A sound view ID for the viewId area.
- No less than one legitimate entry within the dateRanges area.
- No less than one legitimate entry within the metrics area.
View ID
As talked about, there are some things which can be wanted throughout this construct stage, beginning with our viewId. As we have now already outlined beforehand, we simply must name that operate title (VIEW_ID) slightly than including the entire view ID once more.
When you wished to gather knowledge from a unique analytics view sooner or later, you’d simply want to vary the ID within the preliminary code block slightly than each.
Date Vary
Then we will add the date vary for the dates that we need to gather the information for. This consists of a begin date and an finish date.
There are a few methods to put in writing this inside the construct request.
You possibly can choose outlined dates, for instance, between two dates, by including the date in a year-month-date format, ‘startDate’: ‘2022-10-27’, ‘endDate’: ‘2022-11-27’.
Or, if you wish to view knowledge from the final 30 days, you possibly can set the beginning date as ‘30daysAgo’ and the top date as ‘today.’
Metrics And Dimensions
The ultimate step of the essential response name is setting the metrics and dimensions. Metrics are the quantitative measurements from Google Analytics, similar to session depend, session length, and bounce price.
Dimensions are the traits of customers, their periods, and their actions. For instance, web page path, visitors supply, and key phrases used.
There are a variety of totally different metrics and dimensions that may be accessed. I received’t undergo all of them on this article, however they’ll all be discovered along with further data and attributes here.
Something you possibly can entry in Google Analytics you possibly can entry within the API. This contains purpose conversions, begins and values, the browser gadget used to entry the web site, touchdown web page, second-page path monitoring, and inside search, website velocity, and viewers metrics.
Each the metrics and dimensions are added in a dictionary format, utilizing key:worth pairs. For metrics, the important thing might be ‘expression’ adopted by the colon (:) after which the worth of our metric, which may have a particular format.
For instance, if we wished to get a depend of all periods, we’d add ‘expression’: ‘ga:sessions’. Or ‘expression’: ‘ga:newUsers’ if we wished to see a depend of all new customers.
With dimensions, the important thing might be ‘name’ adopted by the colon once more and the worth of the dimension. For instance, if we wished to extract the totally different web page paths, it could be ‘name’: ‘ga:pagePath’.
Or ‘name’: ‘ga:medium’ to see the totally different visitors supply referrals to the location.
Combining Dimensions And Metrics
The actual worth is in combining metrics and dimensions to extract the important thing insights we’re most fascinated about.
For instance, to see a depend of all periods which were created from totally different visitors sources, we will set our metric to be ga:periods and our dimension to be ga:medium.
response = service.studies().batchGet( physique={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}], 'dimensions': [{'name': 'ga:medium'}] }] } ).execute()
Creating A DataFrame
The response we get from the API is within the type of a dictionary, with all the knowledge in key:worth pairs. To make the information simpler to view and analyze, we will flip it right into a Pandas dataframe.
To flip our response right into a dataframe, we first must create some empty lists, to carry the metrics and dimensions.
Then, calling the response output, we are going to append the information from the scale into the empty dimensions record and a depend of the metrics into the metrics record.
It will extract the information and add it to our beforehand empty lists.
dim = [] metric = [] for report in response.get('studies', []): columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) rows = report.get('knowledge', {}).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, worth in zip(metricHeaders, values.get('values')): metric.append(int(worth))
Including The Response Information
As soon as the information is in these lists, we will simply flip them right into a dataframe by defining the column names, in sq. brackets, and assigning the record values to every column.
df = pd.DataFrame() df["Sessions"]= metric df["Medium"]= dim df= df[["Medium","Sessions"]] df.head()
Extra Response Request Examples
A number of Metrics
There’s additionally the flexibility to mix a number of metrics, with every pair added in curly brackets and separated by a comma.
'metrics': [ {"expression": "ga:pageviews"}, {"expression": "ga:sessions"} ]
Filtering
You may as well request the API response solely returns metrics that return sure standards by including metric filters. It makes use of the next format:
if {metricName} {operator} {comparisonValue} return the metric
For instance, should you solely wished to extract pageviews with greater than ten views.
response = service.studies().batchGet( physique={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:pageviews'}], 'dimensions': [{'name': 'ga:pagePath'}], "metricFilterClauses": [{ "filters": [{ "metricName": "ga:pageviews", "operator": "GREATER_THAN", "comparisonValue": "10" }] }] }] } ).execute()
Filters additionally work for dimensions in an identical approach, however the filter expressions might be barely totally different because of the attribute nature of dimensions.
For instance, should you solely need to extract pageviews from customers who’ve visited the location utilizing the Chrome browser, you possibly can set an EXTRACT operator and use ‘Chrome’ because the expression.
response = service.studies().batchGet( physique={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:pageviews'}], "dimensions": [{"name": "ga:browser"}], "dimensionFilterClauses": [ { "filters": [ { "dimensionName": "ga:browser", "operator": "EXACT", "expressions": ["Chrome"] } ] } ] } ] } ).execute()
Expressions
As metrics are quantitative measures, there’s additionally the flexibility to put in writing expressions, which work equally to calculated metrics.
This entails defining an alias to symbolize the expression and finishing a mathematical operate on two metrics.
For instance, you possibly can calculate completions per person by dividing the variety of completions by the variety of customers.
response = service.studies().batchGet( physique={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], "metrics": [ { "expression": "ga:goal1completions/ga:users", "alias": "completions per user" } ] } ] } ).execute()
Histograms
The API additionally allows you to bucket dimensions with an integer (numeric) worth into ranges utilizing histogram buckets.
For instance, bucketing the periods depend dimension into 4 buckets of 1-9, 10-99, 100-199, and 200-399, you need to use the HISTOGRAM_BUCKET order sort and outline the ranges in histogramBuckets.
response = service.studies().batchGet( physique={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}], "metrics": [{"expression": "ga:sessions"}], "dimensions": [ { "name": "ga:sessionCount", "histogramBuckets": ["1","10","100","200","400"] } ], "orderBys": [ { "fieldName": "ga:sessionCount", "orderType": "HISTOGRAM_BUCKET" } ] } ] } ).execute()

In Conclusion
I hope this has supplied you with a primary information to accessing the Google Analytics API, writing some totally different requests, and gathering some significant insights in an easy-to-view format.
I’ve added the construct and request code, and the snippets shared to this GitHub file.
I’ll love to listen to should you strive any of those and your plans for exploring the information additional.
Extra sources:
Featured Picture: BestForBest/Shutterstock