Blog Portfolio

Google Analytics Embed API

Sun, Aug 14, 2016

The Embed API is a JavaScript library that lets you create custom dashboards for Google Analytics that can be hosted on your own site. Why bother creating a dashboard programmatically when you can just create one using Google’s site? Because you can make a better one, control its styling, and accomplish things that cannot be done through Google Analytics alone.

There is a Google tutorial on the Embed API which I used and and enjoyed. I am borrowing from it, but am filling in gaps and adding sections.

To see the types of dashboards that can be built using the API, check out the Embed API demos.


Creating a Client ID

The first thing we are going to do is create a Google Client ID. This ID is needed to perform user authorization.

To get a client ID we need to go to the Google Developer’s Console.

Login to the Console and press the “Create Project” button. Give your project a name and a unique ID.

Now that we have created a project, we can enable the Analytics API.  To do so, click on the APIs link, which is nested under APIs and auth in the left sidebar.

You should see a list of APIs.  Click on the off button to the right of the Analytics API, this will turn it on.

After enabling the Analytics API, click on Credentials, which is under APIs.

Click the blue, Create New Client ID, button.

You see where it says JavaScript origins. This needs to be set to your domain. Do not include any paths.

If you are using localhost, simply set the origins to http://localhost/. It is important to type your host address exactly. If your site is accessed through https, you must include https in the address. Sometimes this can be finicky, so for safe measure include your domain with https, http, and http://www at the beginning.

When this is all set, press Create Client ID.

We are all done with the Dev Console, but you should copy the Client ID or leave the window open for future reference.


The Code

Finally we can start the fun part. Everything up until this point has been setup. It hasn’t been thrilling, but it has been important.

As much as I wanted to wait until the end to give the complete code, it makes more sense for me to do it now and then provide a walkthrough.

<!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>

Walkthrough

We will begin by creating a new html doc and creating three sections with the following ids.
  • auth
  • view-selector
  • data-chart
These sections will contain an authentication button, a view picker, and a chart.

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

To load the Embed API, include the following script block.

<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>

The remaining javascript will be wrapped in the gapi.analytics.ready function. This function is triggered when the API is finished loading.

The first thing we will do is authorize the user using OAUTH 2.0. This will allow the us to display information tied to their google analytics account.

Here is the code for to perform authentication. Make sure to set the CLIENT-ID variable to your Client ID.

// Step 3: Authorize the user.

var CLIENT_ID = 'Client-ID Goes Here';

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

The following function creates a view selector. The container is set to the id of the viewpicker section.

// Step 4: Create the view selector.

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

Here is the code to create the chart. The query specifies what data you want and the chart defines visual aspects.

// 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'
	}
});
The last block of code ties everything together. The viewSelector onChange function updates the chart when a new view is selected.

// 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();
	});
});

Here is a link to Google’s tutorial if you are interested in exploring more.