Skip to content

Instantly share code, notes, and snippets.

@terjesb
Created October 1, 2013 19:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save terjesb/6783675 to your computer and use it in GitHub Desktop.
Save terjesb/6783675 to your computer and use it in GitHub Desktop.
Google Analytics Core Reporting API v3 using Service Account from Clojure
(ns ga-exp.core
(:import
(com.google.api.client.googleapis.auth.oauth2 GoogleCredential$Builder)
(com.google.api.client.googleapis.javanet GoogleNetHttpTransport)
(com.google.api.client.json.jackson2 JacksonFactory)
(com.google.api.services.analytics 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 "example@developer.gserviceaccount.com")
(.setServiceAccountScopes (seq [AnalyticsScopes/ANALYTICS_READONLY]))
(.setServiceAccountPrivateKeyFromP12File (java.io.File. "/Users/example/Downloads/example-privatekey.p12")))]
(.build credential)))
(defn service []
(let [creds (credential)
analytics
(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"]
[com.google.api-client/google-api-client "1.17.0-rc"]
[com.google.http-client/google-http-client "1.17.0-rc"]
[com.google.http-client/google-http-client-jackson2 "1.17.0-rc"]
[com.google.apis/google-api-services-analytics "v3-rev64-1.17.0-rc"]])
@terjesb
Copy link
Author

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.

@JoshSGman
Copy link

Thank you for this!

@caryfitzhugh
Copy link

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

@wuillou8
Copy link

thx a lot!

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