Ways to Connect
There are a few different ways one can connect to the API.
- Installed Application, if there's a legit use case for this let me know.
- Client/Web Application, say you want to connect to someone else's information,
they need to step in when the data is consumed and authorize this. This is
useful in many ways, but it's not what this post is about.
- Service Account, say you really want to do some data work on your data
or you're working for somebody else and they want you to analyze their web
data. And to do that you need to collect the data on some server without
ever connecting to a browser.
The way this works, is ahead of time the Service Account user gets access to
the GA account and procures a key (not unlike an SSH key) and a "fake" (more
on this later) user. With that information then the consumer of the API can
make repeated calls to the API.
Making it Work
This code is actually very, very simple... thanks to the Python Client Library.
Highlevel, we'll make a build a service client with an authenticated request,
then once that service client is "ok" we'll make queries to the GA API.
Building the Authentication Request
Querying the Data
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build
f = file('pk.p12', 'rb')
key = f.read()
account = 'MYACCOUNT'
scope = 'https://www.googleapis.com/auth/analytics.readonly'
creds = SignedJwtAssertionCredentials(account, key, scope)
request = creds.authorize(httplib2.Http())
service_account = build("analytics", "v3", request)
Once we have the account built it's easy to grab that info from GA
start_date = start_date
end_date = end_date
metrics = metrics,
dimensions = dimensions).execute()
So it really isn't a difficult thing to do, but you just need to know what's
going on. Also, make sure you place the email you get from the API console as
a user... it will not work without that. See below for useful links.
Metics and Dimensions
Google API Client Documentation