Let’s start from creating the procedure to authenticate with Google Analytics.

Create a new Google API Project

The first thing we need to do is to create a new project on the Google API console.

From the dashboard click Create a new project.

Give it a name, and you’ll be redirected to the project dashboard:

Add an API by clicking Enable APIs and services.

From the list, search the Google Analytics API:

and enable it

That’s it!

The project is now ready, we can go on to create the authentication credentials.

Create the Authentication Credentials

There are 3 ways to authenticate with the Google APIs:

  • OAuth 2
  • Service to Service
  • API key

API key is less secure and restricted in scope and usage by Google.

OAuth 2 is meant to let your app make requests on behalf of a user, and as such the process is more complicated than needed, and requires exposing URLs to handle callbacks. Way too complex for simple uses.

In a Service to Service authentication model, the application directly talks to the Google API, using a service account, by using a JSON Web Token.

This is the simplest method, especially if you’re building a prototype or an application that talks from your server (like a Node.js app) to the Google APIs. This is the one method I’ll talk about for the test of the article.

Service to Service API

To use this method you need to first generate a JSON Key File through the Google Developers Console.

There is another option which involves downloading a .p12 file and then converting it to a pem file using the openssl command. It’s no longer recommended by Google, just use JSON.

From a project dashboard, click Create credentials, and choose Service Account Key:

Fill the form and choose a “JSON” key type:

That’s it! Google sent you a JSON file:

This is the content of this JSON file, called JSON Key File:

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}

We’ll use some of these values in our program, by adding them as environment variables.

Add the user to Google Analytics

Since we’re using the Service to Service API, you need to add the client_email value we just got in the JSON file to your Google Analytics profile. Go to the Admin panel and click User Management, either on an account or a property. If you do it on a property, you’ll only have access to the single property (you can add more than one later).

Do it on an account to have access to all your properties at the same time.

And add the email you found in the client_email key in the JSON file, and make sure you click the “Read and Analyze” permission:


Go to the next lesson