Query Google Analytics API with a service account in Python

I recently needed to display a visitor counter on a website by some client’s weird demand. Maybe the 90s are coming back. Anyway, I thought it makes sense to query Google Analytics directly, but Google’s API example were not really helping. After some digging around, I finally found a solution. You’ll need oauth2client and google-api-python-client for it to work. Then follow these instructions on Google Developers to create a service account that only has access to the API without the need for a human to request some oauth token. It will give you a private key to work with.

5 thoughts on “Query Google Analytics API with a service account in Python”

  1. Hi, this is very useful for me as I need to access a google api permanently. However when I run the code, I think the credentials does not return an access token and therefore there’s no output from the program:

    (credentials.access_token is empty)

    How to fix this issue?

  2. Hi @julian, thanks for this post.
    I have to implement something similar to this (pageviews instead of visitors), but I’m getting the following error when privatekey going to be used

    PKCS12 format is not supported by the PyCrpto library. Try converting to a “PEM” (openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) or using PyOpenSSL if native code is an option.

    then I tried to use openssl command, but it is asking me a password


    $ openssl pkcs12 -in privatekey.p12 -nodes -nocerts > privatekey.pem
    Enter Import Password:

    any idea which password I should use?

    thanks in advance!

  3. The password for the private key is “notasecret”. It’s set as a default argument in the __init__() method of the SignedJwtAssertionCredentials class.

  4. Hi Julian,

    I am trying to do something similar to what you have done with the above code and was wondering if you would be willing to discuss via email. I would really appreciate some help!

    Thanks,
    Scott

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">