Management API -“实验”开发者指南

本文介绍了如何使用 Management API v3 来访问和修改实验数据。

简介

Google Analytics(分析)的“实验”处于帐户层级结构的第四级,也是最低的一级;“实验”没有子实体。每个“实验”资源都有一个数据视图(配置文件)资源作为其在层级结构中的父级。

Management API 提供的“实验”资源包括与 Google Analytics(分析)实验的配置和状态相关的信息。此资源用于运行实验

开始之前

本指南说明了如何使用以下编程语言来访问 Google Analytics(分析)API:
  • Java
  • Python
  • PHP

  • 请阅读客户端库页面,查看与 Management API 配合使用的编程语言客户端库的完整列表。
  • 请阅读参考指南,了解如何在没有客户端库的情况下访问该 API

每个客户端库提供单个 Analytics 服务对象来访问所有的 Management API 数据。要创建服务对象,您通常需要完成以下步骤:

  1. Google Developers Console 中注册您的应用。
  2. 授予访问 Google Analytics(分析)数据的权限。
  3. 创建一个 Analytics 服务对象。

如果您未能完成上述步骤,请停止操作,并阅读 Google Analytics(分析)API 入门教程。该教程将为您详细介绍构建 Google Analytics(分析)API 应用的最初几个步骤。完成这些步骤后,您就可以使用本指南执行实际任务了。

以下代码段从第 3 步(创建一个 Analytics 服务对象)继续,包含一个用来存储已获授权的服务对象的变量。

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

PHP 库会将所有 API 结果作为一个关联数组来返回。要返回真正的对象,您可以调用客户端 useObject 方法,如上例所示。

创建了 Analytics 服务对象后,您就可以对 Management API 发出请求了。

注意:同一个 Analytics 服务对象也可以用来访问 Core Reporting API

概览

“实验”集合和资源让您可以获取、列出、插入、更新、修补和删除授权用户的实验。要进行这些操作,您首先需要创建一个与该 API 配合使用的 Analytics 服务对象。

支持的方法

  • List 方法,列出数据视图(配置文件)的实验。
  • Get 方法,获取单个实验。
  • Insert 方法,为用户插入一个新实验。
  • Update 方法,更新实验以修改其配置和/或状态。
  • Patch 方法,修补实验以修改其配置和/或状态。
  • Delete 方法,删除实验。

List

应用可以通过针对 Analytics 服务对象调用“实验”的 list 方法,请求列出用户的所有实验。此方法需要 accountIdwebPropertyIdprofileId 作为参数。

例如,下面的代码请求列出帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1 和数据视图(配置文件)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();
}

  • 如果查询成功,该 API 将返回 200 状态代码以及所请求的数据。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。

调用“实验”的 list 方法的结果存放在 experiments 对象中。下列代码展示了如何遍历这些结果。请阅读“实验”参考,查看对“实验”中所有属性的说明。

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

应用可以通过针对 Analytics 服务对象调用“实验”的 get 方法,请求获取授权用户的单个实验。此方法需要 accountIdwebPropertyIdprofileIdexperimentId 作为参数。

例如,下面的代码请求获取帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1、数据视图(配置文件)ID 为 56789 和实验 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();
}

  • 如果查询成功,该 API 将返回 200 状态代码,以及所请求的实验。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。

Insert

应用可以通过针对 Analytics 服务对象调用“实验”的 insert 方法,来为用户插入一个新实验。此方法需要 accountIdwebPropertyIdprofileID 和一个主体。该主体是一个采用“实验”资源形式的对象,其将决定所插入实验的配置。

下面是一个示例主体,其代表了某个“实验”资源:

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');

准备好实验主体后,下面的示例代码将插入了一个帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1 和数据视图(配置文件)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();
}
  • 如果查询成功,该 API 将返回 200 状态代码,并在响应正文中包含一个实验资源。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。

Update

应用可以通过针对 Analytics 服务对象调用“实验”的 update 方法,对用户的现有实验进行更新。此方法需要 accountIdwebPropertyIdprofileIdexperimentId 和一个主体作为参数。该主体是一个采用“实验”资源形式的对象,其中包含的参数和插入一个实验所需要的参数相同。

下面是一个示例主体,其代表了某个“实验”资源:

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');

准备好实验主体后,下面的示例代码将更新帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1、数据视图(配置文件)ID 为 56789 和实验 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();
}
  • 如果查询成功,该 API 将返回 200 状态代码,并在响应正文中包含一个实验资源。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。

Patch

应用可以通过针对 Analytics 服务对象调用“实验”的 patch 方法,对用户的现有实验进行修补。此方法需要 accountIdwebPropertyIdprofileIdexperimentId 和一个主体作为参数。该主体是一个对象,采用“实验”资源子集的形式,其中只包含需要更新的参数。

下面是一个示例主体,其代表了某个“实验”资源的一个子集,将把“实验”的状态更新为 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');

准备好实验主体后,下面的示例代码将修补帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1、数据视图(配置文件)ID 为 56789 和实验 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();
}
  • 如果查询成功,该 API 将返回 200 状态代码,并在响应正文中包含一个实验资源。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。

Delete

应用可以通过针对 Analytics 服务对象调用“实验”的 delete 方法来删除用户的实验。此方法需要 accountIdwebPropertyIdprofileIdexperimentId 作为参数。

例如,下面的代码将删除一个帐户 ID 为 1234、网络媒体资源 ID 为 UA-1234-1、数据视图(配置文件)ID 为 56789 和实验 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();
}
  • 如果查询成功,该 API 将返回 200 状态代码。delete 方法将返回空白的响应正文。
  • 如果出错,该 API 将返回除了 200 之外的其他状态代码,以及一条说明错误原因的描述性消息。请阅读参考指南中的错误响应部分,查看所有状态代码的完整列表和含义。