Skip to content

Instantly share code, notes, and snippets.

Created October 1, 2013 19:20
What would you like to do?
Google Analytics Core Reporting API v3 using Service Account from Clojure
(ns ga-exp.core
( GoogleCredential$Builder)
( GoogleNetHttpTransport)
( JacksonFactory)
( Analytics$Builder AnalyticsScopes)))
(def HTTP_TRANSPORT (GoogleNetHttpTransport/newTrustedTransport))
(def JSON_FACTORY (JacksonFactory.))
(defn credential []
(let [credential
(doto (GoogleCredential$Builder.)
(.setTransport HTTP_TRANSPORT)
(.setJsonFactory JSON_FACTORY)
(.setServiceAccountId "")
(.setServiceAccountScopes (seq [AnalyticsScopes/ANALYTICS_READONLY]))
(.setServiceAccountPrivateKeyFromP12File ( "/Users/example/Downloads/example-privatekey.p12")))]
(.build credential)))
(defn service []
(let [creds (credential)
(doto (Analytics$Builder. HTTP_TRANSPORT JSON_FACTORY creds)
(.setApplicationName "My App")
(.setHttpRequestInitializer creds))]
(.build analytics)))
(defn q []
(let [analytics (service)
data (.data analytics)
ga (.ga data)
table (.get ga "ga:EXAMPLE" "2013-10-01" "2013-10-01" "ga:totalValue")
query (.. table
(setDimensions "ga:source,ga:medium,ga:transactionId")
(setStartIndex (int 10001))
(setMaxResults (int 10000)))]
(.execute query)))
(defproject ga-exp "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.5.1"]
[ "1.17.0-rc"]
[ "1.17.0-rc"]
[ "1.17.0-rc"]
[ "v3-rev64-1.17.0-rc"]])
Copy link

terjesb commented Oct 1, 2013

"User does not have any Google Analytics account" (insufficientPermissions) indicates that the service account email has not been given Read & Analyze permission to the profile. Note that it can take a few minutes after it has been added until it works.

Copy link

Thank you for this!

Copy link

oh this is so wonderful to find. thanks a lot!

Copy link

thx a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment