Using the Google Analytics API with Go
It’s simple, but this should make it simpler
November 25, 2018
Over the past few years there were several occasions on which I had to access the Analytics API using Go. This should be, and is, fairly simple. However, each time it took me too long to get it up and running. So for a future reference to myself, and for anyone else out there struggling with the Google Analytics API in Go, I wrote the steps down.
So for this first step we need to set up Analytics in our Google API Console. This is described in the following tutorial, just follow step 1, and then feel free to come back to this article.
https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php
Alright, welcome back! By now you should have the following:
- A beautiful gserviceaccount.com email address, like <name>@<project>.iam.gserviceaccount.com
- Have given this email address access to a Google Analytics account / property / profile
- A JSON file containing your credentials
Perfect, now, let’s move on to the code.
The code
Warning, horrible code ahead!
package main
import (
"fmt"
"io/ioutil"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/analytics/v3"
)
func main() {
key, _ := ioutil.ReadFile("key.json")
jwtConf, err := google.JWTConfigFromJSON(
key,
analytics.AnalyticsReadonlyScope,
)
p(err)
httpClient := jwtConf.Client(oauth2.NoContext)
svc, err := analytics.New(httpClient)
p(err)
accountResponse, err := svc.Management.Accounts.List().Do()
p(err)
var accountId string
fmt.Println("Found the following accounts:")
for i, acc := range accountResponse.Items {
if i == 0 {
accountId = acc.Id
}
fmt.Println(acc.Id, acc.Name)
}
webProps, err := svc.Management.Webproperties.List(accountId).Do()
p(err)
var wpId string
fmt.Println("\nFound the following properties:")
for i, wp := range webProps.Items {
if i == 0 {
wpId = wp.Id
}
fmt.Println(wp.Id, wp.Name)
}
profiles, err := svc.Management.Profiles.List(accountId, wpId).Do()
p(err)
var viewId string
fmt.Println("\nFound the following profiles:")
for i, p := range profiles.Items {
if i == 0 {
viewId = "ga:" + p.Id
}
fmt.Println(p.Id, p.Name)
}
fmt.Println("\nTime to retrieve the real time users of this profile")
metrics := "rt:activeUsers"
rt, err := svc.Data.Realtime.Get(viewId, metrics).Do()
p(err)
fmt.Println(rt.Rows)
}
func p(err error) {
if err != nil {
panic(err)
}
}
This code loops over your accounts, their associated web properties, and their associated profiles. And then retrieves the amount of currently active users on that specific profile right now.
Make sure the JSON file retrieved from the Google API Console is in the same directory as your Go code, and make sure
it’s called key.json
. Now run the file as: go run main.go
(unless you called it differently of course)
Here is the output, in my case.
Found the following accounts:
1234567 machiel.me
Found the following properties:
UA-1234567-01 https://machiel.me
Found the following profiles:
98765432 www.machiel.me
Time to retrieve the real time users of this profile
[[1]] # If there are none, this would be []
Wow, a total of one user on my website right now! That’s me!
Anyway, that’s pretty much it. The Analytics API is way more extensive, but the API itself is fairly well documented. This was just to get you (or future me) up and running with the Google Analytics API in Go.
Enjoy!