Querying the Google Analytics API using OAUTH

Today I want to talk about querying the Google Analytics API. In the previous posts, we looked at querying Twitter and YouTube APIs. With each of these, we didn’t need to jump through the OAuth hoops of misery that are required for the Google, Facebook, Linkedin etc.. APIs. So today, I wanted to talk about how we might go about doing that.

We have a few options when we come to authenticating, which you will see in the Developer Console when you come to create your keys. In this article, I am going to cover the implementation of OAuth client ID and Service account as I don’t see the use case of the API Key.

INSTALLED APP FLOW

So first, we have the OAuth client ID. When you walk through the creation process in the Google Developer Console, it will give you the option to download your JSON key file, we’ll use that in this top block.

First off, as always we’re going to import our libraries. We then define the Google Analytics profile ID that we are going to track.

We then, assign scopes to the request. A scope is the permission level that will be provisioned to your app. Here, we’ve given the readonly scope, which does as it says on the tin & gives the app permissions to read data only.

Next, we create the flow, where we pass the app authentication & the required permissions (scopes) and run the flow.

Once you’ve run the flow, you’ll get the token back which you can use to authenticate on behalf of your user.

So in the request URI (which you can generate via the Google Query Explorer) you inject your token and profile ID.

You can then handle the output with Pandas, giving you a nice tabular way to deal with your data.

FLOW (WEB APP)

The above is great if you’ve installed an app locally & you can redirect to localhost. If you’re running this on a webserver, we can use the flow method. This prompts the user to login & provides a token back, which we can then use to query.

In the below, we kick off a flow again, using the same secrets.json file and applying the same scopes as we did above.

Next, we get the user to authenticate against our auth_url and paste the code provided into the box. That then gives us the ability to extract a token and then query the API.

SERVICE ACCOUNT FLOW

The alternate method is through service accounts, which gives you access to the Google Analytics data that your service account ID has been provisioned to see. With this, we again import some libraries (different to the ones above).

We then, again define our ID of the Google Analytics object that we want to track. Next, we generate our credentials from our JSON client secrets file and extract the token.

And then, just like above, we run our API call and wrangle the data in Pandas.

And that is it! It’s not a hugely complicated process, but the documentation is really poor. So hopefully a worked example will help you.