Displaying selected metrics with Google Analytics API via service account

January 27, 2020 read
Displaying selected metrics with Google Analytics API via service account
Web Development
Data Science

On platforms such as teachsomebody.com where authors can post courses and articles, there is the need to show how their
posts are faring in terms of number of page views, number of sessions, etc. Users who register to become authors or publishers on teachsomebody will have access to their own analytics dashboard where they see metrics on only the courses and articles they have published on the platform. In this post, I will explain how we retrieve number of page views per author from Google Analytics via a platform-wide service account. To allow an application to retrieve data from Google Analytics Management API (and many other Google APIs), these steps are in order: 

  1. Create a service account for the project in Google developer console. 
  2. Create and download the key for the service account.
  3. Enable Google Analytics Management API for the service account.
  4. Decide on the OAuth 2.0 scope of the Google API. In this post, we will only allow read only of google analytics data https://developers.google.com/identity/protocols/googlescopes#analyticsreportingv4
  5. Decide which metrics you want to show authors. On TeachSomebody, we currently show the number of page views per month. See https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/ to explore the possible metrics and dimensions.

In the subsequent sections, I will show how you can make request to the Google
Analytics API using the Google API client Python library: google-api-python-client.

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
credentials = service_account.Credentials.from_service_account_file('', scopes=SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)

resp = analytics.reports().batchGet(
	body={
      'reportRequests': [
         {
            'viewId': '',
            'dateRanges': [
               {'startDate': '30daysAgo', 'endDate': 'today'}
            ],
            'metrics': [
               {'expression': 'ga:sessions'}, 
               {'expression': 'ga:avgSessionDuration'},
               {'expression': 'ga:pageviews'}
            ],
            'dimensions': [
               {'name': 'ga:country'}, 
               {'name': 'ga:pagePath'}
            ],
            'dimensionFilterClauses': [
               {
                   'filters': [
                      {
                         'dimensionName': 'ga:pagePath',
                         'operator': ,
                         'expressions': 
                      }
                   ]
               }
           ]
        }
     ]
	},
	quotaUser=<user_id>
	}
)

The viewId is a unique identification of a property view in Google Analytics. To know how to see your view ID see: https://keyword-hero.com/documentation/finding-your-view-id-in-google-analytics 

The dimensionFilterClauses allow to retrieve metrics relating to a specify partial or an exact page urls (filter_expressions). See the possible operators at: https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#operator

The quotaUser is used to get the quota per user so as to extend the overall API query quota limits.

Sample output for the metrics of a specified page is as shown below:

{
    "reports": [
        {
            "columnHeader": {
                "dimensions": [
                    "ga:country",
                    "ga:pagePath"
                ],
                "metricHeader": {
                    "metricHeaderEntries": [
                        {
                            "name": "ga:sessions",
                            "type": "INTEGER"
                        },
                        {
                            "name": "ga:avgSessionDuration",
                            "type": "TIME"
                        },
                        {
                            "name": "ga:pageviews",
                            "type": "INTEGER"
                        }
                    ]
                }
            },
            "data": {
                "totals": [
                    {
                        "values": [
                            "0",
                            "0.0",
                            "150"
                        ]
                    }
                ]
            }
        }
    ]
}

The values in the totals represent the metrics in the specified order.

User profile image

Created by

Evans Boateng Owusu

Evans is a Computer Engineer and cloud technology enthusiast. He has a Masters degree in Embedded Systems (focusing on Software design) from the Technical University of Eindhoven (The Netherlands) and a Bachelor of Science in Electronic and Computer Engineering from the Polytechnic University of Turin (Italy). In addition, he has worked for the high-tech industry in the the Netherlands and other large corporations for over seven years.


© Copyright 2024, The BoesK Partnership