Access Google Analytics API with OAuth token

Notes on adding a Google Service worker that enables you to query Google Analytics with an access token.

Create service user and add key file on server side

Step 1: Generate JSON key

Go to https://console.developers.google.com/

Create a project with your name

Select Region closest to you

Click create

Go to the project and click Enable API

Select Analytics API

Click Enable

Click Go to Credentials

Select Analytics API, Other UI and Application data –> What Credentials do I need

Type an account name. Note down the service account ID for later

Role: Project viewer and Project browser

A JSON will be downloaded. Keep this safe – you have the only copy, and it grants you access to your Analytics data

Allow service user read access to your google analytics

Step 2: Give permissions

Add permissions to your google analytics for that service worker. Think of as service worker as a separate account. It will need to be added in your google analytics -> Admin -> User management

Extract access key from key file

Step 3: Code to extract access key

In order to query the API, you need an access token. This token will only last half an hour, so you’ll need some code that extracts the temporary access key, using the JSON-credentials you created in step 1.

The code below gives you an accessToken that can be used with requests to the API.

Step 4: How to use the access key

Use the Access key to read from your Google Analytics. The API can be explored here, and you’ll see the URL you need to request (and where to put the access key). You can now go ahead and knock yourself out.