-
Notifications
You must be signed in to change notification settings - Fork 62
Authentication
The newest Google Analytics API, v3, only supports authentication using OAuth2. It won't work with your account username and password. There's a few steps to get started.
- Go to https://console.developers.google.com/project and create a new project. Call it anything you like, e.g. "My Google Analytics Sandbox". This registers your application with Google.
- Click on your project, go to
APIs & auth
and thenPermissions
. Enable the Analytics API for your project. - Go to
APIs & auth
and thenCredentials
. - On the credentials page, find your Client ID and Client Secret or generate new ones. If you need to generate new credentials, ask for offline use / use in an installed application.
Optionally, save the project credentials we grabbed in Step 1 to environment variables. This'll ensure you don't accidentally put your secrets in your code.
Put something like this in your ~/.zshrc
or ~/.bashrc
:
export GOOGLE_ANALYTICS_CLIENT_ID=...
export GOOGLE_ANALYTICS_CLIENT_SECRET=...
Then reload your environment using (e.g.) source ~/.bashrc
.
Now we're ready to authorize and authenticate.
On the command-line, type:
# pick any project identity you like -- this can but doesn't have
# to be the same name as the one you chose for your project in
# the Google Developer Console
googleanalytics authorize --identity myproject
-
google-analytics
will look through your environment variables and your operating system's keychain for existing credentials. - If nothing's there, you will be prompted for a client id and client secret.
- Finally, a new browser window will open and you will be asked to give your project access to your account.
Alternatively, in a Python REPL, type:
import googleanalytics as ga
ga.authenticate(identity='myproject', interactive=True, save=True)
If you don't want the package to save your credentials in the OS keychain, try this instead:
import googleanalytics as ga
credentials = ga.authorize(interactive=True)
# save these credentials somewhere for later use
print(credentials.serialize())
We've made a project (step 1), we gave our project read-only authorization to our Google Analytics data (step 3). Now let's authenticate.
import googleanalytics as ga
# if you authorized via the command-line or added the `save=True` keyword
# argument you can log in by specifying just your identity
accounts = ga.authenticate(identity='myproject')
# alternatively, specify everything by hand
# (note: putting secrets right inside your code is not the
# safest thing to do)
accounts = ga.authenticate(
client_id='....apps.googleusercontent.com',
client_secret='...',
refresh_token='...',
)
accounts
is a list of user accounts that your credentials have given you access to.
If you already know which account, web property and profile you'd like to access, you can tell ga.authenticate
to return the correct profile rather than a list of all accounts:
import googleanalytics as ga
profile = ga.authenticate(
account='debrouwere.org',
webproperty='http://debrouwere.org',
profile='debrouwere.org'
)
report = profile.query.metrics('pageviews').range('2014-10-01', '2014-10-31').get()
print report['pageviews']
Our Python module also has experimental support for service accounts. Support is currently limited to Python 3.
Service accounts are an alternative authentication option which can be used to give a project access to just one Google Analytics domain account, rather than all of the Google Analytics accounts to which your personal Google account has access. (One Google account can have access to many different Google Analytics accounts.) You might know this concept as "two-legged OAuth".
To use service accounts, first install PyCrypto, e.g. using pip3 install pycrypto
.
Instead of a client secret and client id, authenticate with a client email and private key. You can generate these credentials in the Developer Console. Click on "Create a new Client ID" and then select the "Service account" option (rather than the "Installed application" option which we would use otherwise.)
Then add the client email address as a user in the Google Analytics web interface.
ga.authenticate(client_email=client_email, private_key=private_key)
Using a service account is recommended when developing a server application that will grab data from a single Google Analytics account rather than data from various third-party users (including yourself). The advantage of service accounts is that they avoid exposing all of the Google Analytics accounts you might personally have access to, instead giving the application access to just one.
If you'd like to store the OAuth2 tokens so you don't have to ask for permission every time you run your code, you absolutely can. On the command-line, this is the default behavior: once authenticated, we save your credentials. In Python, pass save=True
and interactive=True
:
import googleanalytics as ga
accounts = ga.authenticate(save=True, interactive=True)
If you'd prefer saving client_id
, client_secret
and refresh_token
somewhere yourself, that's possible too:
import os
import json
import googleanalytics as ga
if os.path.exists('credentials.json'):
credentials = json.load(open('credentials.json'))
else:
# authorize your code to access the Google Analytics API
# (this will be interactive, as you'll need to confirm
# in a browser window)
credentials = ga.authorize()
# turn the credentials object into a plain dictionary
credentials = credentials.serialize()
json.dump(credentials, open('credentials.json', 'w'))
ga.authenticate(**credentials)
- Authentication
- Querying
- Common Queries
- Working With Reports
- On The Command Line
- Python API documentation