Hide

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 Developers 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.
  2. This API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application 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.

      To create an OAuth 2.0 token, click Create new Client ID, provide the required information where requested, and click Create Client ID.

      You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

      Web applications

      A web application is accessed by web browsers over a network.

      • Applications that use JavaScript to access the Analytics API must specify authorized JavaScript origins. The origins identify the domains from which your application can send API requests.
      • Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses.

      Service accounts

      A service account is used in an application that calls APIs on behalf of an application that does not access user information. This type of application needs to prove its own identity, but it does not need a user to authorize requests. The Google Accounts documentation contains more details about service accounts.

      Installed applications

      An installed application runs on a desktop computer or handheld device. You can create OAuth 2.0 credentials for Android, Chrome, iOS, and other installed applications.

      Android

      You need to specify your Android app's package name and SHA1 fingerprint.

      1. In the Package name field, enter your Android app's package name.
      2. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.
        keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

        The Keytool prints the fingerprint to the shell. For example:

        $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
        Enter keystore password: Type "android" if using debug.keystore
        Alias name: androiddebugkey
        Creation date: Aug 27, 2012
        Entry type: PrivateKeyEntry
        Certificate chain length: 1
        Certificate[1]:
        Owner: CN=Android Debug, O=Android, C=US
        Issuer: CN=Android Debug, O=Android, C=US
        Serial number: 503bd581
        Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
        Certificate fingerprints:
           MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
           SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
           SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
           Signature algorithm name: SHA1withRSA
           Version: 3

        Copy the SHA1 fingerprint, which is highlighted in the example above.

      3. Paste the SHA1 fingerprint into the form where requested.
      4. Click Create.

      Chrome application

      You need to specify the Application ID for your Chrome app or extension. Use the Google Chrome Identity API to obtain that ID.

    • iOS

      You need to specify the app's Bundle ID and App Store ID.

      • The application's Bundle ID is the bundle identifier as listed in the app's .plist file. For example: com.example.myapp.
      • The application's App Store ID is in the app's iTunes URL so long as the app was published in the Apple iTunes App Store. For example, in the app URL http://itunes.apple.com/us/app/google+/id447119634, the App Store ID is 447119634.

      Other

      The Developers Console does not require any additional information to create OAuth 2.0 credentials for other types of installed applications.

    • Public API access: 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 API keys. If the key type that you need does not already exist, create an API key by selecting Create New Key and then selecting the appropriate key type. Then enter the additional data for that key type and click Create.

      Server keys

      Create and use a server key if your application runs on a server. Do not use this key outside of your server code. For example, do not embed it in a web page. To prevent quota theft, restrict your key so that requests are only allowed from your servers' source IP addresses.

      Browser keys

      Create and use a browser key if your application runs on a client, such as a web browser. To prevent your key from being used on unauthorized sites, only allow referrals from domains you administer.

      iOS keys

      Create and use an iOS key if your application runs on iOS devices. Google verifies that each request originates from an iOS application that matches one of the bundle identifiers you specify. An app's .plist file contains its bundle identifier. Example: com.example.MyApp

      Android keys

      Create and use an Android key if your application runs on Android devices. To do so, you need to specify the SHA1 fingerprints and package names of the application using that key.

      1. In the Package name field, enter your Android app's package name.
      2. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.
        keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

        The Keytool prints the fingerprint to the shell. For example:

        $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
        Enter keystore password: Type "android" if using debug.keystore
        Alias name: androiddebugkey
        Creation date: Aug 27, 2012
        Entry type: PrivateKeyEntry
        Certificate chain length: 1
        Certificate[1]:
        Owner: CN=Android Debug, O=Android, C=US
        Issuer: CN=Android Debug, O=Android, C=US
        Serial number: 503bd581
        Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
        Certificate fingerprints:
           MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
           SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
           SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
           Signature algorithm name: SHA1withRSA
           Version: 3

        Copy the SHA1 fingerprint, which is highlighted in the example above.

      3. Paste the SHA1 fingerprint into the form where requested.
      4. Click Create.

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

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.