Google Analytics

Management API - Experiments Developer Guide

This document explains how to use the Management API v3 to access and modify Experiments data.

  1. Introduction
  2. Before You Begin
  1. Supported Methods
    1. List
    2. Get
    3. Insert
    4. Update
    5. Patch
    6. Delete
More

Introduction

A Google Analytics Experiment is at the fourth and lowest level in the account hierarchy; experiments have no child entities. Each Experiments resource has a single View (Profile) resource as its parent in the hierarchy.

The Experiments resource provided by the Management API includes information related to the configuration and status of a Google Analytics experiment. This resource is used for running experiments.

Before You Begin

This guide demonstrates how to access the Google Analytics API using the following programming languages:
  • Java
  • Python
  • PHP

  • Read the client libraries page for a complete list of programming language specific client libraries that work with the Management API.
  • Read the Reference Guide to access the API without a client library

Each client library provides a single Analytics service object to access all Management API data. To create the service object you generally have to go through the following steps:

  1. Register your application in the Google Developers Console.
  2. Authorize access to Google Analytics data.
  3. Create an Analytics service object.

If you haven't completed these steps, please stop and read the Hello Google Analytics API Tutorial. This tutorial will walk you through the initial steps of building a Google Analytics API application. Once complete, you will be able to use this guide to perform real-world tasks.

The following code snippet continues from step 3: Create an Analytics service object and contains a variable to store an authorized service object.

Java

Analytics analytics = // Read Hello Analytics Tutorial for details.

Python

analytics = # Read Hello Analytics Tutorial for details.

PHP

$client = // Read Hello Analytics Tutorial for details.

// Return results as objects.
$client->setUseObjects(true);

$analytics = new apiAnalyticsService($client);

The PHP library will return all the API results as an associative array. To return real objects instead, you can call the client useObject method as demonstrated in the example above.

Once you create an Analytics service object, you are ready to make requests to the Management API.

Note: The same Analytics service object can also be used to access the Core Reporting API.

Overview

The Experiment collection and resource allows you to get, list, insert, update, patch, and delete experiments for an authorized user. To use any of these methods, you first need to create an Analytics service object to work with the API.

Supported Methods

  • List a view's (profile) experiments.
  • Get a single experiment.
  • Insert a new experiment for the user.
  • Update an experiment to modify its configuration and/or status.
  • Patch an experiment to modify its configuration and/or status.
  • Delete an experiment.

List

An application can request a list of experiments for the authorized user by calling the list method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, and a profileId as parameters.

For example, the following code requests a list of all Experiments for account ID 1234, web property ID UA-1234-1, and view (profile) ID 56789.

Java

try {
  Experiments experiments = analytics.management().experiments().list("1234",
        "UA-1234-1", "56789").execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  experiments = analytics.management().experiments().list(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789').execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiments = $analytics->management_experiments
                           ->listManagementExperiments('1234', 'UA-1234-1', '56789');
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}

  • If the query was successful, the API will return a 200 status code along with the requested data.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.

The results of the list method for experiments are stored in the experiments object. The following code shows how to iterate through them. Read the Experiments reference for an explanation of all the properties of an Experiment.

Java

for (Experiment experiment : experiments.getItems()) {
  System.out.println("Account ID: " + experiment.getAccountId());
  System.out.println("Web Property ID: " + experiment.getWebPropertyId());
  System.out.println("View (Profile) ID: " + experiment.getProfileId());
  System.out.println("Experiment ID: " + experiment.getId());
  System.out.println("Description: " + experiment.getDescription());
  System.out.println("Status:" + experiment.getStatus());
  System.out.println("Winner Found:" + experiment.getWinnerFound());
  System.out.println("Start Time:" + experiment.getStartTime());
  System.out.println("End Time:" + experiment.getEndTime());

  System.out.println("Experiment Variations:");
  for (Variations variation : experiment.getVariations()) {
    System.out.println(" Name: " + variation.getName());
    System.out.println(" URL: " + variation.getUrl());
    System.out.println(" Status: " + variation.getStatus());
    System.out.println(" Weight: " + variation.getWeight());
    System.out.println(" Won: " + variation.getWon());

  }
}

Python

for experiment in experiments.get('items', []):
  print 'Account ID        = %s' % experiment.get('accountId')
  print 'Web Property ID   = %s' % experiment.get('webPropertyId')
  print 'View (Profile) ID = %s' % experiment.get('profileId')
  print 'Experiment ID     = %s' % experiment.get('id')
  print 'Description       = %s' % experiment.get('description')
  print 'Status            = %s' % experiment.get('status')
  print 'Winner Found      = %s' % experiment.get('winnerFound')
  print 'Start Time        = %s' % experiment.get('startTime')
  print 'End Time          = %s' % experiment.get('endTime')

  print ' Experiment Variations:'
  for variation in experiment.get('variations', []):
    print ' Name   = %s' % variation.get('name')
    print ' URL    = %s' % variation.get('url')
    print ' Status = %s' % variation.get('status')
    print ' Weight = %s'  % variation.get('weight')
    print ' Won    = %s' % variation.get('won')

PHP

$items = $experiments->getItems();

if (count($items) != 0) {
  foreach($items as $experiment) {
    $html .= <<<HTML
<pre>
Account ID         = {$experiment->getAccountId()}
Web Property ID    = {$experiment->getWebPropertyId()}
View (Profile) ID  = {$experiment->getProfileId()}
Experiment ID      = {$experiment->getId()}
Description        = {$experiment->getDescription()}
Status =           = {$experiment->getStatus()}
Winner Found       = {$experiment->getWinnerFound()}
Start Time         = {$experiment->getStartTime()}
End Time           = {$experiment->getEndTime()}
    HTML;

    foreach($experiment->getVariations() as $variation) {
      $html .= <<<HTML

Variation:
  Name   =  {$variation->getName()}
  URL    =  {$variation->getUrl()}
  Status =  {$variation->getStatus()}
  Weight =  {$variation->getWeight()}
  Won    =  {$variation->getWon()}
</pre>
      HTML;
    }
  }
}

Get

An application can request a single experiment for the authorized user by calling the get method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, a profileId, and experimentId as parameters.

For example, the following code requests a single Experiment for account ID 1234, web property ID UA-1234-1, view (profile) ID 56789, and experiment ID CDR997cT4TYOv4PODWS0MGdg.

Java

try {
  Experiment experiment = analytics.management().experiments().get("1234",
        "UA-1234-1", "56789", "CDR997cT4TYOv4PODWS0MGdg").execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  experiments = analytics.management().experiments().get(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789',
      experimentId='CDR997cT4TYOv4PODWS0MGdg').execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiments = $analytics->management_experiments
                           ->get('1234',
                                 'UA-1234-1',
                                 '56789',
                                 'CDR997cT4TYOv4PODWS0MGdg');
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}

  • If the query was successful, the API will return a 200 status code along with the requested experiment.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.

Insert

An application can insert a new experiment for a user by calling the insert method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, a profileID, and a body. The body is an object in the form of an Experiments resource and will determine the configuration of the inserted experiment.

The following is an example body representing an experiment resource:

Java

// Variation 1
Variations variation1 = new Experiment.Variations();
variation1.setUrl("http://www.examplepetstore.com");
variation1.setName("Original");

// Variation 2
Variations variation2 = new Experiment.Variations();
variation2.setUrl("http://www.examplepetstore.com/2");
variation2.setName("Gus' Version");

List variationList =
        Lists.newArrayList(variation1, variation2);

// Experiment Body
Experiment experimentBody = new Experiment();
experimentBody.setName("Landing Page Experiment");
experimentBody.setStatus("READY_TO_RUN");
experimentBody.setVariations(variationList);
experimentBody.setObjectiveMetric("ga:goal1Completions");

Python

experiment_body = {
    'name': 'Landing Page Experiment',
    'status': 'READY_TO_RUN',
    'variations': [
        {
            'url': 'http://www.examplepetstore.com',
            'name': 'Original'
        },
        {
            'url': 'http://www.examplepetstore.com/2',
            'name': 'Gus version'
        }
    ],
    'objectiveMetric': 'ga:goal1Completions'
}

PHP

// Variation 1
$variation1 = new google_ExperimentVariations();
$variation1->setUrl('http://www.examplepetstore.com');
$variation1->setName('Original');

// Variation 2
$variation2 = new google_ExperimentVariations();
$variation2->setUrl('http://www.examplepetstore.com/2');
$variation2->setName('Gus\' Version');

// Experiment Body
$experimentBody = new google_Experiment();
$experimentBody->setName('Landing Page Experiment');
$experimentBody->setStatus('READY_TO_RUN');
$experimentBody->setVariations(array($variation1, $variation2));
$experimentBody->setObjectiveMetric('ga:goal1Completions');

With the experiment body prepared, the following example code inserts a new experiment for account ID 1234, web property ID UA-1234-1, and view (profile) ID 56789.

Java

try {
  Experiment experiment = analytics.management().experiments().insert("1234",
        "UA-1234-1", "56789", experimentBody).execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  experiment = service.management().experiments().insert(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789',
      body=experiment_body).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiment = $analytics->management_experiments
                          ->insert('1234',
                                   'UA-1234-1,
                                   '56789',
                                   $experimentBody);
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error '  . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
  • If the query was successful, the API will return a 200 status code along with a Experiments resource in the response body.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.

Update

An application can update a user's existing experiment by calling the update method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, a profileId, an experimentId, and a body as parameters. The body is an object in the form of an Experiments resource that includes all of the same parameters that are required to insert an experiment.

The following is an example body representing an experiment resource:

Java

// Variation 1
Variations variation1 = new Experiment.Variations();
variation1.setUrl("http://www.examplepetstore.com");
variation1.setName("Original");

// Variation 2
Variations variation2 = new Experiment.Variations();
variation2.setUrl("http://www.examplepetstore.com/2");
variation2.setName("Gus' Version");

List variationList =
        Lists.newArrayList(variation1, variation2);

// Experiment Body
Experiment experimentBody = new Experiment();
experimentBody.setName("Landing Page Experiment");
experimentBody.setStatus("RUNNING");
experimentBody.setVariations(variationList);
experimentBody.setObjectiveMetric("ga:goal1Completions");

Python

experiment_body = {
    'name': 'Landing Page Experiment',
    'status': 'RUNNING',
    'variations': [
        {
            'url': 'http://www.examplepetstore.com',
            'name': 'Original'
        },
        {
            'url': 'http://www.examplepetstore.com/2',
            'name': 'Gus version'
        }
    ],
    'objectiveMetric': 'ga:goal1Completions'
}

PHP

// Variation 1
$variation1 = new google_ExperimentVariations();
$variation1->setUrl('http://www.examplepetstore.com');
$variation1->setName('Original');

// Variation 2
$variation2 = new google_ExperimentVariations();
$variation2->setUrl('http://www.examplepetstore.com/2');
$variation2->setName('Gus\' Version');

// Experiment Body
$experimentBody = new google_Experiment();
$experimentBody->setName('Landing Page Experiment');
$experimentBody->setStatus('RUNNING');
$experimentBody->setVariations(array($variation1, $variation2));
$experimentBody->setObjectiveMetric('ga:goal1Completions');

With the experiment body prepared, the following example code updates the experiment for account ID 1234, web property ID UA-1234-1, view (profile) ID 56789, and experiment ID CDR997cT4TYOv4PODWS0MGdg.

Java

try {
  Experiment experiment = analytics.management().experiments().update("1234",
        "UA-1234-1", "56789", "CDR997cT4TYOv4PODWS0MGdg",
        experimentBody).execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  experiment = service.management().experiments().update(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789',
      experimentId='CDR997cT4TYOv4PODWS0MGdg',
      body=experiment_body).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiment = $analytics->management_experiments
                          ->update('1234',
                                   'UA-1234-1,
                                   '56789',
                                   'CDR997cT4TYOv4PODWS0MGdg',
                                   $experimentBody);
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error '  . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
  • If the query was successful, the API will return a 200 status code along with a Experiments resource in the response body.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.

Patch

An application can patch a user's existing experiment by calling the patch method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, a profileId, an experimentId, and a body as parameters. The body is an object in the form of a subset of an Experiment resource that includes only the parameters that require updating.

The following is an example body representing a subset of an experiments resource that will update the status of the Experiment to RUNNING:

Java

// Experiment Patch
Experiment experimentPatch = new Experiment();
experimentPatch.setStatus("RUNNING");

Python

experiment_patch = {
    'status': 'RUNNING',
}

PHP

// Experiment Patch
$experimentPatch = new google_Experiment();
$experimentPatch->setStatus('RUNNING');

With the experiment body prepared, the following example code patches the experiment for account ID 1234, web property ID UA-1234-1, view (profile) ID 56789, and experiment ID CDR997cT4TYOv4PODWS0MGdg.

Java

try {
  Experiment experiment = analytics.management().experiments().patch("1234",
        "UA-1234-1", "56789", "CDR997cT4TYOv4PODWS0MGdg",
        experimentPatch).execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  experiment = service.management().experiments().patch(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789',
      experimentId='CDR997cT4TYOv4PODWS0MGdg',
      body=experiment_patch).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiment = $analytics->management_experiments
                          ->patch('1234',
                                   'UA-1234-1,
                                   '56789',
                                   'CDR997cT4TYOv4PODWS0MGdg',
                                   $experimentPatch);
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error '  . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
  • If the query was successful, the API will return a 200 status code along with a Experiments resource in the response body.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.

Delete

An application can delete a user's experiment by calling the delete method for Experiments on the Analytics service object. The method requires an accountId, a webPropertyId, a profileId, and an experimentId as parameters.

For example, the following code deletes an experiment for account ID 1234, web property ID UA-1234-1, view (profile) ID 56789, and experiment ID CDR997cT4TYOv4PODWS0MGdg.

Java

try {
  Delete delete = analytics.management().experiments().delete("1234",
      "UA-1234-1", "56789", "CDR997cT4TYOv4PODWS0MGdg").execute();

} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

Python

try:
  delete = analytics.management().experiments().delete(
      accountId='1234',
      webPropertyId='UA-1234-1',
      profileId='56789',
      experimentId='CDR997cT4TYOv4PODWS0MGdg').execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print ('There was an error in constructing your query : %s' % error)

except HttpError, error:
  # Handle API errors.
  print ('Arg, there was an API error : %s : %s' %
         (error.resp.status, error._get_reason()))

PHP

try {
  $experiment = $analytics->management_experiments
                          ->delete('1234',
                                   'UA-1234-1,
                                   '56789',
                                   'CDR997cT4TYOv4PODWS0MGdg');
} catch (apiServiceException $e) {
  print 'There was an Analytics API service error '
  . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
  print 'There was a general API error '
    . $e->getCode() . ':' . $e->getMessage();
}
  • If the query was successful, the API will return a 200 status code. The delete method returns an empty response body.
  • If there was an error, the API will return with status code other than 200, as well as a descriptive message describing what caused the error. Read the Error Response section in the reference guide for a full list of all the status codes and what they mean.



Authentication required

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

Signing you in...

Google Developers needs your permission to do that.