Embed API

Server-side Authorization

Demo Overview

This demo shows how you can use server-side authorization to display your Google Analytics data to users without granting them access to your Google Analytics account.

The charts below show usage data for the site you're visiting now, Google Analytics Demos & Tools. Notice how you do not have to be logged in to see this data!

How it works

You can recreate the demo above by following the instructions and using the code below. If you want to know more, check out the Embed API documentation on our developers site.

Step 1: Create a service account and download the JSON key

Follow the steps in the Google Identity Platform documentation to create a service account from the Google Developer Console.

Once the service account is created, you can click the Generate New JSON Key button to create and download the key and add it to your project.

Important!  Make sure to store your JSON key file privately and securely. Do not check it in to a public repository or store it on a public server.

Step 2: Add the service account as a user in Google Analytics

The service account you created in the previous step has an email address that you can add to any of the Google Analytics views you'd like to request data from. It's generally best to only grant the service account read-only access.

Step 3: Use the JSON key data to request an access token

The following python script uses the oauth2client module that comes with the Google API Client Library for Python to extract OAuth2 credentials from the JSON key file and use those credentials to request an access token.

You can install the Google API Client Library for Python using pip by running the following command:

sudo pip install --upgrade google-api-python-client

Once the library is installed you can add the following python module to your project and invoke the get_access_token() method to get an access token that you can use to authorize the Embed API.

# service-account.py

from oauth2client.service_account import ServiceAccountCredentials

# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'

# Defines a method to get an access token from the ServiceAccount object.
def get_access_token():
  return ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILEPATH, SCOPE).get_access_token().access_token

Step 4: Load the Embed API library.

<script>
(function(w,d,s,g,js,fs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
  js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>

Step 5: Add HTML containers to host the dashboard components.

<div id="chart-1-container"></div>
<div id="chart-2-container"></div>

Step 6: Write the dashboard code.

Use the access token obtained in step 3 to authorize the Embed API.

Important!  When you add an access token to the source code of your page, your site's visitors could use that access token to run any query the service account could run. If your account contains sensitive information, considering adding the service account only to a specific view. You may also want to add a view filter to limit what data the service account can access.

<script>

gapi.analytics.ready(function() {

  /**
   * Authorize the user with an access token obtained server side.
   */
  gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
    }
  });


  /**
   * Creates a new DataChart instance showing sessions over the past 30 days.
   * It will be rendered inside an element with the id "chart-1-container".
   */
  var dataChart1 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:100367422', // <-- Replace with the ids value for your view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:sessions,ga:users',
      'dimensions': 'ga:date'
    },
    chart: {
      'container': 'chart-1-container',
      'type': 'LINE',
      'options': {
        'width': '100%'
      }
    }
  });
  dataChart1.execute();


  /**
   * Creates a new DataChart instance showing top 5 most popular demos/tools
   * amongst returning users only.
   * It will be rendered inside an element with the id "chart-3-container".
   */
  var dataChart2 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:100367422', // <-- Replace with the ids value for your view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:pageviews',
      'dimensions': 'ga:pagePathLevel1',
      'sort': '-ga:pageviews',
      'filters': 'ga:pagePathLevel1!=/',
      'max-results': 7
    },
    chart: {
      'container': 'chart-2-container',
      'type': 'PIE',
      'options': {
        'width': '100%',
        'pieHole': 4/9,
      }
    }
  });
  dataChart2.execute();

});
</script>