Getting Started

Overview

This document will guide you through a full example of how to use the Embed API. Once completed, you will have an application that looks like this.

A screenshot of example covered in this guide
A screenshot of the example covered in this guide.

Creating a Simple Dashboard

You can get the sample application running on your server by following these 2 easy steps:

  1. Create a new client ID
  2. Copy and paste the code

After you have this application up and running, the next section will explain in detail how all the pieces fit together.

Create a New Client ID

The Embed API handles almost all of the authorization process for you by providing a one-click sign-in component that uses the familiar OAuth 2.0 flow. In order to get this button working on your page you'll need a client ID.

If you've never created a client ID, you can do so by following these instructions.

As you go through the instructions, it's important that you not overlook these two critical steps:

  • Enable the Analytics API
  • Set the correct origins

The origins control what domains are allowed to use this code to authorize users. This prevents other people from copying your code and running it on their site.

For example, if your website is hosted on the domain example.com, make sure to set the following origin for your client ID http://example.com. If you want to test your code locally, you'll need to add the origin for your local server as well, for example: http://localhost:8080.

Copy and Paste the Code

Once you have your client ID with the proper origins set you're ready to create the demo. Just copy and paste the following code into an HTML file on your server plug in your client ID where it says: "Insert your client ID here".

<!DOCTYPE html>
<html>
<head>
  <title>Embed API Demo</title>
</head>
<body>

<!-- Step 1: Create the containing elements. -->

<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>

<!-- Step 2: Load the library. -->

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

<script>
gapi.analytics.ready(function() {

  // Step 3: Authorize the user.

  var CLIENT_ID = 'Insert your client ID here';

  gapi.analytics.auth.authorize({
    container: 'auth-button',
    clientid: CLIENT_ID,
  });

  // Step 4: Create the view selector.

  var viewSelector = new gapi.analytics.ViewSelector({
    container: 'view-selector'
  });

  // Step 5: Create the timeline chart.

  var timeline = new gapi.analytics.googleCharts.DataChart({
    reportType: 'ga',
    query: {
      'dimensions': 'ga:date',
      'metrics': 'ga:sessions',
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
    },
    chart: {
      type: 'LINE',
      container: 'timeline'
    }
  });

  // Step 6: Hook up the components to work together.

  gapi.analytics.auth.on('success', function(response) {
    viewSelector.execute();
  });

  viewSelector.on('change', function(ids) {
    var newIds = {
      query: {
        ids: ids
      }
    }
    timeline.set(newIds).execute();
  });
});
</script>
</body>
</html>

Code Walkthrough

This section walks you through, step-by-step, exactly what is going on in the code provided for the sample application. Once you have a grasp of how it works, you should be able to create your own.

Step 1: Create the component containers

Most of the Embed API components will render something visually onto your page. The way you control where those components go is by creating containers for them. In the example application we have an auth button, a view selector, and a chart. Each of these components gets rendered inside the following HTML elements:

<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>

When creating a component, you tell it what container to use by its ID attribute, as you'll see in the later examples.

Step 2: Load the library

The Embed API can be loaded with the following snippet.

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

When the library is fully loaded, any callbacks passed to gapi.analytics.ready will be invoked.

<script>
gapi.analytics.ready(function() {
  // Put your application code here...
});
</script>

Step 3: Authorize the user

The Embed API handles almost all of the authorization process for you by providing a one-click sign-in component that uses the familiar OAuth 2.0 flow. To get this button working on your page you'll need to pass in a container reference and your client ID.

gapi.analytics.auth.authorize({
  container: 'auth-button',
  clientid: CLIENT_ID,
});

This will generate a button inside of the element with the 'auth-button' ID that takes care of the authorization flow for you.

Step 4: Create the view selector

The View selector component can be used to obtain the ids of a particular view, so you can run a report for it.

To create a view selector, all you need is the container reference that you created in step 1.

var viewSelector = new gapi.analytics.ViewSelector({
  container: 'view-selector'
});

This creates the view selector component, but it doesn't yet render it on the page. To do that you need to call execute(), which is handled in step 6.

Step 5: Create the timeline chart

The Embed API provides you with a chart component that is both a Google chart as well as a report object in one. This greatly simplifies the process for displaying data as the chart object will run your reports behind the scene and automatically update itself with the results.

To create a chart component you'll need to specify the API query parameters as well as the chart options. Within the chart options is a reference to the ID of the container you created in step 1.

var timeline = new gapi.analytics.googleCharts.DataChart({
  reportType: 'ga',
  query: {
    'dimensions': 'ga:date',
    'metrics': 'ga:sessions',
    'start-date': '30daysAgo',
    'end-date': 'yesterday',
  },
  chart: {
    type: 'LINE',
    container: 'timeline'
  }
});

As with the view selector, this creates the chart component but to render it to the page you need to call execute(), which will be explained in the next step.

Step 6: Hook up the components to work together

Embed API components emit events when various things happen such as successful authorization, selecting a new view, or a chart being fully rendered.

The example application in this guide waits to render the view selector until after authorization has happened, and it updates the timeline chart whenever a new view is selected from the view selector.

gapi.analytics.auth.on('success', function(response) {
  viewSelector.execute();
});

viewSelector.on('change', function(ids) {
  var newIds = {
    query: {
      ids: ids
    }
  }
  timeline.set(newIds).execute();
});

For a complete list of all the events the various components emit, check out the API reference.

Next Steps

This guide walked you through how to create a basic visualization with the Embed API. If you'd like to learn more, check out the API reference to get a full sense of what is possible.