Google API with service accounts and JWT tokens
I wanted to see what bills are popular on Congress Matters, the congress-done-right site g0v.tw developed. Since it's a modern angularjs site accessing the Congress API, there's no traditional counter on the server side. But luckily google analytics is sort of that counter-as-a-service that we (and probably everyone) already use. Since all we care about is metrics under the /bills path, the analytics api can also do the filtering for us.
Danny Su wrote about Accessing Google API using Service Account, which can be further simplified: (in LiveScript, admire the elegance of backcalls escaping from the callback pyramid of doom)
jwt = new googleapis.auth.JWT do
SERVICE_ACCOUNT_EMAIL
KEYFILE_PEM
null
['https://www.googleapis.com/auth/analytics.readonly']
err, client <- googleapis.discover 'analytics', 'v3' .execute
err, result <- jwt.authorize
console.log result
err, result <- client.analytics.data.ga.get do
'ids': 'ga:XXXXXX'
'start-date': '2014-01-21'
'end-date': '2014-01-30'
'metrics': 'ga:visits'
'dimensions': 'ga:pagePathLevel2'
'sort': '-ga:visits'
'filters': 'ga:pagePathLevel1==/bills/'
'max-results': 25
.with-auth-client jwt
.execute
if err
console.log 'Error', err
console.log result
Note that you do have to add the service account to all levels of the three analytics access control (account, resource, view)
BTW, this week's popular is the Social Enterprise Incorporation Act and the Land Administration Agent Act Amendment. Check out the bill diff!