Using the Google Analytics Reporting API v4 with Rails

A short overview of available documentation

Andrew Haines
Dec 18, 2017 · 2 min read

Google’s latest Analytics Reporting API v4 is nearly two years old. But there’s almost no documentation for implementing it via Ruby/Rails. This post is a quick attempt to help piece together what’s available for those new to the topic.

The first place to look is Google’s official google-api-ruby-client gem, which includes a few key definitions, especially helpful for getting valid responses to requests.

For what it’s worth, my gist from early 2017 is still one of the top hits on the subject. It’s based on a GitHub issue by 23tux, and on using the google-api-client and omniauth-google-oauth2 gems to access the API and Oauth2. (Both gems are pretty well documented in their own right, so I won’t worry about including that here.)

Here’s another example, by Cory Foy, showing how to connect with a slightly different setup.

What you actually do with that response.reports depends on your use case. You can get the structure of the response body in the official docs, here.

{
"reports": [
{
"columnHeader": {
"metricHeader": {
"metricHeaderEntries": [
{
"name": "ga:users",
"type": "INTEGER"
}
]
}
},
"data": {
"isDataGolden": true,
"maximums": [
{
"values": [
"98"
]
}
],
"minimums": [
{
"values": [
"98"
]
}
],
"rowCount": 1,
"rows": [
{
"metrics": [
{
"values": [
"98"
]
}
]
}
],
"totals": [
{
"values": [
"98"
]
}
]
}
}
]
}

Based on that, you could grab the total number of sessions in the query from my gist above, for example, using some simple predication like: response.reports.first.data.totals.first.values.first.to_i.

The advanced use cases in the v4 API are impressive. But they get complex pretty fast. It’d be nice to know whether anyone has compiled some helpful Rails query/response templates for any typical configurations. I’d be glad to share them, if so.

Fiat Insight

Building products with purpose. Since 2010.

Andrew Haines

Written by

Co-founder and COO at Fiat Insight

Fiat Insight

Building products with purpose. Since 2010.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade