You use Google Analytics to track user behavior and traffic on your website. Instead of looking at Google's built-in reporting tools you want to be able to merge this data with other insights yourself. But how do you go about this? This blog post will show you how to authenticate the connection between Displayr and the Google Analytics API so that you can start importing and visualizing your data.

Everyone who has access to Google Analytics also has access to their API. As with many APIs, the most challenging part of this equation can be the authentication process. There are a handful of different methods of authentication via R, each with their pros and cons (see here for examples) but the common element is the googleAuthR package which is already installed in Displayr.

The most basic approach uses the ga_auth() function. You'll need to log into your Google Analytics account and have access to a browser and your working directory to save a cached authentication file. You can set this up to auto-authenticate but it isn’t practical when you aren’t running commands directly from your own computer and storing files to your local drive or server.

As we are setting this up in a cloud-based platform, the user won’t have access to the server to save any authentication file. The solution is to set up a Google service account and authenticate via a linked JSON credentials file which can be downloaded from the Google API console. Here we will instead parse the contents of this file via R code.

Set up your Google Service account

If you have never used the Google Analytics API before then you will need to first set up a Google Service account. If you have already done this, then skip to the next section. To do this:

  1. Go to the Google service accounts page.
  2. Select Create to start setting up your Google Cloud Platform project, if you do not already have one.
  3. Give it a suitable project name then press Create again.
  4. You will then be given a unique project account ID. On the following screen, click Enable APIs and get credentials like keys (under Getting Started).
  5. At the top, click ENABLE APIS AND SERVICES
  6. Type "Google Analytics" and click on the box for Google Analytics Reporting API.
  7. Click Enable.

Now that the API has been enabled for this project, we need to set up the service account and JSON key:

  1. Click Credentials on the left pane (it will look like a key).
  2. Then click Create credentials > Service account key.
  3. Select New service account (if you don't already have one), give it an appropriate name and assign the role (e.g. Project > Owner).
  4. Ensure JSON is selected for the Key type and press Create.

The JSON file will now be downloaded to your browser.

Use an existing Google Service account

If you already have an existing Google Service account then the following section applies instead, otherwise you can skip this part and move on to the next section.

  1. Go to the Google service accounts page.
  2. Click Select.
  3. Choose your project.
  4. Click the icon under the Actions column for your service account and select Create Key.
  5. In the next window, make sure the Key type is JSON and click Create.

The JSON file will now be downloaded to your browser.

Give permission to the Service account email address

The service account we created will also provide an email address linked to your project ID which will appear in this format: In order for access to work via this service account, you'll need to add the generated email address to your Google Analytics account as a user with appropriate access to view the data. To do this:

  1. Log in to your Google Analytics account.
  2. Go to Admin > View > User Management.
  3. Click the + button and select Add new users.
  4. Enter the email address for your service account.
  5. Ensure you've ticked Read and Analyze for this email address.
  6. Click Add.

Create your authentication token in Displayr

Whenever you want to make a call to Google Analytics in Displayr using R code, you need to have a token available. In this section I describe the code to use to make this token.

Depending on how you want to set up your data, you need to follow different steps. If you want to add the Google Analytics data as a data set, you should use Home > New Data Set, and structure the code to generate your data set like the accompanying image on the left.

That is, within the output you first place code which authenticates and generates the token, and then the rest of your code makes calls to the Google Analytics API.

Alternatively, you can bring in your Google Analytics data as an R Output. This can be helpful to check the structure of the data that is being returned and debug any errors in your code. Once you have prototyped, you may then want to use an R data set instead. You should structure the code in your output in the same way as depicted to the left.

Now, I'll describe how to set up the R Code to create token part.

In this example, I use an R output so that I can test that everything is working correctly before pulling the data:

  1. Select Insert > R Output (Analysis Group).
  2. Paste the below into the R CODE window of the Object Inspector.
  3. Open the JSON file that you downloaded from Google in the sections above in a text editor.
  4. Copy and paste the contents of the JSON file to replace the 12 lines of code below secret.txt = '. Be sure to keep the braces ({}) and single quotation marks as they are in my example.
  5. Press Automate.
scope = ""

secret.txt = '
"type": "service_account",
"project_id": "XXXXX",
"private_key_id": "XXXXXX",
"private_key": "-----BEGIN PRIVATE KEY-----XXXXXXX-----END PRIVATE KEY-----",
"client_email": "",
"client_id": "XXXXXX",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": ""
secrets = jsonlite::fromJSON(gsub("\n", "", secret.txt))

endpoint = httr::oauth_endpoints("google")
secrets$private_key = gsub("-----BEGIN PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----\n", secrets$private_key)
secrets$private_key = gsub("-----END PRIVATE KEY-----", "\n-----END PRIVATE KEY-----\n", secrets$private_key)
google_token = httr::oauth_service_token(endpoint, secrets, scope)
token <- googleAuthR:::.auth$get_cred()

In this code, I begin by setting the scope so that it's pointing to the API.  I then use jsonlite's fromJSON function to parse the text from JSON to a recognizable R format before authenticating the connection using httr's oauth and googleAuthR's auth functions. Now we have authenticated the connection. In my next blog, we pull data from the API and make an easy visualization.