I’m currently building out a metrics dashboard and I wanted to incorporate Google Analytics data along with my own data. Google maintains a Python client so I figured this would be easy. Grab some OAuth 2 keys and away we go.
Sadly that’s not the case. It took a bit of digging and piecing together numerous articles and blog posts to get everything working.
So here’s how to do it…
2) Next, activate the Google Analytics API for your project.
3) Then create your credentials by creating a new service account.
4) When you create the credentials, you will automatically download a P12 key file (.p12). Save this with your Python application as you’ll be using it shortly.
5) The next step is SUPER important – even though you’ve created API credentials, you still need to give them permission to access your Google Analytics account. Follow the steps outlined here to add a new user to your Google Analytics account, using the email address generated as part of the service account above.
6) Now that we’ve got all of that set up, we’re ready to move over to Python. First step is to install the requirements:
7) Since we’re going to use the P12 key, we’ll also need to install pyOpenSSL:
8) Finally, it’s time for the code…