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.

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.