Metadata API - Developer Guide

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

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

To acquire an API key:

  1. Open the Credentials page in the API Console.
  2. This API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth 2.0: Whenever your application requests private user data, it must send an OAuth 2.0 token along with the request. Your application first sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

      Note: Since this API doesn't have any methods that require OAuth 2.0 authorization, you might only need to obtain API keys, which are described below. However, if your application calls other APIs that require user authorization, then you still need OAuth 2.0 credentials.

      For more information, see the OAuth 2.0 documentation.

    • API keys: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

      The API supports several types of restrictions on API keys. If the API key that you need doesn't already exist, then create an API key in the Console by clicking Create credentials  > API key. You can restrict the key before using it in production by clicking Restrict key and selecting one of the Restrictions.

To keep your API keys secure, follow the best practices for securely using API keys.

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>

Column Attributes

The Metadata API response includes an attributeNames property that lists all valid column attributes. Each column has an attributes property that includes a subset of attributes that are applicable to the column.

The following table is the complete list of valid attributes:

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

The uiName attribute is the dimension or metric name that is used in Google Analytics user interfaces (e.g. the web interface).

The following snippet shows how to retrieve the UI name of a column:

function getColumnName(column) {
  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:percentNewSessions is ga:newSessions / ga:sessions.

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

Added in API Version

Use the addedInApiVersion attribute to check whether a column can be used in a reporting API of a specified version. For example, call the following function to verify that the column can be used in the Core Reporting API V3:

function isAllowedInV3(column) {
  return column.attributes.addedInApiVersion < 4;
}

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.