Google Analytics

Metadata API - Developer Guide

This document explains important concepts about using the Metadata API to access the list and attributes of Google Analytics columns.

  1. Introduction
  2. Before you begin
    1. Registration & API Key
  1. Use Cases
    1. Deprecated Columns
    2. Column Names
    3. Templatized Columns
    4. Calculated Columns
    5. Columns and Segments
    6. ETag

Introduction

The Metadata API returns the list of columns (i.e. dimensions and metrics) exposed in the Google Analytics reporting APIs and their attributes. If you are new to the API, read the Metdata API Overview for an introduction to the Metadata API.

Before You Begin

All Google Analytics APIs are accessed in a similar manner. Before you begin with the Metadata API you should:

  • Read the client libraries page for a complete list of programming language specific client libraries that work with the API.
  • Read the Reference Guide to learn about the API interface and accessing data without a client library.

Each client library provides a single analytics service object to access all Metadata API data. To create the service object for use with the Metadata API you generally have to go through the following steps:

  1. Register your application in the Google Cloud Console.
  2. Create an Analytics service object and set the API Key.

Registration & API Key

Your application needs to identify itself every time it sends a request to the Analytics API, by including an API Key with each request.

Acquiring and using an API key

  1. Go to the Google Cloud Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the displayed list of APIs, make sure all the APIs you are using show a status of ON.
  4. In the sidebar on the left, select Registered apps.
  5. Select an application.
  6. Expand the Browser Key or Server Key sections.

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

The API key is safe for embedding in URLs; it doesn't need any encoding.

The following code snippets illustrate how to set the API Key for various client libraries:

Java

import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.http.javanet.NetHttpTransport;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsRequestInitializer;

public class ApiKeySample {
  private static final String API_KEY = "YOUR API KEY";

  public static void main(String[] args) {
    NetHttpTransport netHttpTransport = new NetHttpTransport();
    JacksonFactory jacksonFactory = new JacksonFactory();

    // Set the API Key
    AnalyticsRequestInitializer analyticsInitializer = new AnalyticsRequestInitializer(API_KEY);

    // Build the Analytics Service object
    Analytics analytics = new Analytics.Builder(netHttpTransport, jacksonFactory, null)
        .setAnalyticsRequestInitializer(analyticsInitializer)
        .setApplicationName("ApiKeySample")
        .build();

    // Start coding cool things.
  }
}

Python

from apiclient.discovery import build

API_KEY = 'YOUR API KEY'

def main(argv):
  # Set the API Key and build the Analytics service object.
  service = build('analytics', 'v3', developerKey=API_KEY)

  # Start coding cool things.

PHP

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';

const API_KEY = 'YOUR API KEY'

$client = new Google_Client();

// Set the API Key
$client->setDeveloperKey($API_KEY);

// Build the Analytics Service object.
$analytics = new google_AnalyticsService($client);

// Start coding cool things.

JavaScript

<!--
  Method 1:
  Using the Google APIs Client Library for JavaScript
-->
<script>
var apiKey = 'YOUR API KEY';

function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  gapi.client.load('analytics', 'v3', makeRequest);
}

function makeRequest() {
  // Start coding cool things.
}
</script>
<script src="//apis.google.com/js/client.js?onload=handleClientLoad"></script>


<!--
  Method 2:
  Using REST and callback parameter
-->
<script>
function render() {
  // Place your awesome code here.
}
</script>

<!-- Replace RESOURCE with the path to the Google Analytics resource you're querying. -->
<script src="https://www.googleapis.com/analytics/v3/RESOURCE/?key=YOUR_API_KEY&callback=render"></script>

Use Cases

The Metadata API can be used to solve the following use cases:

Deprecated Columns

If a column (i.e. a dimension or metric) is deprecated then its status attribute will be set to DEPRECATED.

The following snippet shows how to use the status attribute to check if a column is deprecated:

function isDeprecated(column) {
  return column.attributes.status == 'DEPRECATED';
}

If a column is renamed/removed then its status attribute will be set to DEPRECATED and it may have a replacedBy attribute set to the Id of the replacement column.

The following snippet shows how to use the replacedBy attribute to get the Id of the replacement column:

function getReplacementId(column) {
  return column.attributes.replacedBy;
}

Column Names

There are some dimension and metrics that have different UI names depending on whether you're viewing reports for a WEB or APP view (profile) type. The uiName attribute is the name used for web views (profiles). Columns that have a different name for app views (profiles) will have an appUiName attribute in addition to the uiName attribute.

The following snippet shows how to retrieve the web and app name of a column:

function getWebName(column) {
  return column.attributes.uiName;
}

function getAppName(column) {
  if (column.attributes.appUiName) {
    return column.attributes.appUiName;
  }
  return column.attributes.uiName;
}

Templatized Columns

Templatized columns include dimensions or metrics with a numeric index. For example, ga:goalXXStarts, ga:dimensionXX, ga:metricXX, etc. A templatized column will have minTemplateIndex and maxTemplateIndex attributes that define the index range.

The following snippet shows how to check if a column is templatized:

function isTemplatized(column) {
  return !!column.attributes.minTemplateIndex ||
         !!column.attributes.maxTemplateIndex;
}

The following snippet shows how to retrieve a list of valid IDs for a templatized column:

function getTemplatizedIdList(column) {
  var columnIdList = [];
  var columnId = column.id;

  if (isTemplatized(column)) {
    minIndex = parseInt(column.attributes.minTemplateIndex);
    maxIndex = parseInt(column.attributes.maxTemplateIndex);

    for (var i = minIndex; i <= maxIndex; i++) {
      columnIdList.push(columnId.replace('XX', i));
    }
  }
  return columnIdList;
}

Calculated Columns

A column that is derived from a calculation of other columns will have a calculation attribute. E.g. The calculation for ga:percentNewVisits is ga:newVisits / ga:visits.

The following example shows how to check if a column is calculated and how to retrieve the calculation for a column:

function isCalculated(column) {
  return !!column.attributes.calculation;
}

function getCalculation(column) {
  return column.attributes.calculation;
}

Columns and Segments

The allowedInSegments attribute allows you to check whether a column can be used in the segment query parameter.

The following example shows how to determine if a column can be used in segments:

function isAllowedInSegments(column) {
  return !!column.attributes.allowedInSegments;
}

ETag

An ETag is included in every Metadata API response. The ETag is an identifier that can be used to cache and update Metadata API responses. This is important because columns (i.e dimensions and metrics) data can remain unchanged for long periods of time and it's ineffiecient to make uncessary requests and updates when cached data can be used.

If you store the ETag of a column collection it can be primarily be used in 2 ways: to check if a cached Metadata API response is up-to-date, and to include it as part of a Metadata API request.

Checking a Cached Response

If you compare the ETag value returned from a Metadata API response and it's equivalent to the ETag for a cached resource then the cached version is current. If the ETags aren't equivalent then update your application and refresh the cache with the latest response.

If you want to retrieve only the ETag value from the Metadata API, set the fields query parameter to etag when making a request. See an example.

Using an ETag with an API Request

If you have a cached version of a column collection then you can include its ETag value in a Metadata API request by setting the If-None-Match HTTP header field. The Metadata API will check the ETag value and either respond with an updated version of the resource and a 200 OK HTTP status or an empty response with a 304 Not Modified status if your cached version is current.




Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.