Ejemplos

En este artículo se ofrecen ejemplos de las funciones que incluye la versión 4 de la API de informes de Google Analytics.

Dimensiones y métricas

A continuación se muestra una solicitud simple que incluye solo algunas dimensiones y métricas. En el Explorador de dimensiones y métricas encontrarás una lista completa de las dimensiones y métricas disponibles. Las dimensiones y métricas son objetos repetidos configurables que se pasan en el cuerpo de la solicitud POST.

Java

// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate("2015-06-15");
dateRange.setEndDate("2015-06-30");

// Create the Metrics object.
Metric sessions = new Metric()
    .setExpression("ga:sessions")
    .setAlias("sessions");

//Create the Dimensions object.
Dimension browser = new Dimension()
    .setName("ga:browser");

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
    .setViewId("XXXX")
    .setDateRanges(Arrays.asList(dateRange))
    .setDimensions(Arrays.asList(browser))
    .setMetrics(Arrays.asList(sessions));

ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest()
    .setReportRequests(requests);

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
        {
          "startDate":"2015-06-15",
          "endDate":"2015-06-30"
        }],
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"
        }]
      }]
  }
).execute()

PHP

// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2015-06-15");
$dateRange->setEndDate("2015-06-30");

// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");

//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges($dateRange);
$request->setDimensions(array($browser));
$request->setMetrics(array($sessions));

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analyticsreporting->reports->batchGet( $body );

JavaScript

api.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
      {
        "startDate":"2015-06-15",
        "endDate":"2015-06-30"
      }],
    "metrics":[
      {
        "expression":"ga:sessions"
      }],
    "dimensions": [
      {
        "name":"ga:browser"
      }]
  }]
} ).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
      {
        "startDate":"2015-06-15",
        "endDate":"2015-06-30"
      }],
    "metrics":[
      {
        "expression":"ga:sessions"
      }],
    "dimensions": [
      {
        "name":"ga:browser"
      }]
    }]
}

Varios periodos

Este es un ejemplo que incluye varios periodos:

Java

// Create DateRange objects.
DateRange march = new DateRange()
    .setStartDate("2015-03-01")
    .setEndDate("2015-03-31");

DateRange january = new DateRange()
    .setStartDate("2015-01-01")
    .setEndDate("2015-01-31");

// Create the Metrics object.
Metric sessions = new Metric()
    .setExpression("ga:sessions")
    .setAlias("sessions");

// Create the Dimensions object.
Dimension browser = new Dimension()
    .setName("ga:browser");

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
    .setViewId("XXXX")
    .setDateRanges(Arrays.asList(march, january))
    .setDimensions(Arrays.asList(browser))
    .setMetrics(Arrays.asList(sessions));

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
      {
        "startDate":"2015-01-01",
        "endDate":"2015-01-31"
      },
      {
        "startDate":"2015-03-01",
        "endDate":"2015-03-31"
      }],
      "dimensions":[
      {
        "name":"ga:browser"
      }],
      "metrics":[
      {
        "expression":"ga:sessions"
      }]
    }]
  }
).execute()

PHP

// Create DateRange objects.
$march = new Google_Service_AnalyticsReporting_DateRange();
$march->setStartDate("2015-03-01");
$march->setEndDate("2015-03-31");

$january = new Google_Service_AnalyticsReporting_DateRange();
$january->setStartDate("2015-01-01");
$january->setEndDate("2015-01-31");

...

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges(array($march, $january));
$request->setDimensions(array($browser));
$request->setMetrics(array($sessions));

JavaScript

api.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "startDate":"2015-01-01",
      "endDate":"2015-01-31"
    },
    {
      "startDate":"2015-03-01",
      "endDate":"2015-03-31"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    }],
    "metrics":[
    {
      "expression":"ga:sessions"
    }]
  }]
} ).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "startDate":"2015-01-01",
      "endDate":"2015-01-31"
    },
    {
      "startDate":"2015-03-01",
      "endDate":"2015-03-31"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    }],
    "metrics":[
    {
      "expression":"ga:sessions"
    }]
  }]
}

Al analizar la respuesta de una solicitud con varios periodos, los resultados se devuelven como una matriz de dateRangeValues.

Java

private static void printResults(List<Report> reports) {
  for (Report report : reports) {
    ColumnHeader header = report.getColumnHeader();
    List<String> dimensionHeaders = header.getDimensions();
    List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
    List<ReportRow> rows = report.getData().getRows();

    for (ReportRow row : rows) {
      List<String> dimensions = row.getDimensions();
      List<DateRangeValues> metrics = row.getMetrics();
      for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
        System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
      }

      for (int j = 0; j < metrics.size(); j++) {
        System.out.print("Date Range (" + j + "): ");
        DateRangeValues values = metrics.get(j);
        for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
          System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
        }
      }
    }
  }
}

Python

def printResults(response):
  for report in response.get("reports", []):
    columnHeader = report.get("columnHeader", {})
    dimensionHeaders = columnHeader.get("dimensions", [])
    metricHeaders = columnHeader.get("metricHeader", {}).get("metricHeaderEntries", [])
    rows = report.get("data", {}).get("rows", [])

    for row in rows:
      dimensions = row.get("dimensions", [])
      dateRangeValues = row.get("metrics", [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ": " + dimension

      for i, values in enumerate(dateRangeValues):
        print "    Date range index: " + str(i)
        for metric, value in zip(metricHeaders, values.get("values")):
          print "    "  + metric.get("name") + ": " + value

PHP

function printResults(&$reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];
        $values = $metrics[$j];
        print("Metric type: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
          print($entry->getName() . ": " . $value . "\n");
        }
      }
    }
  }
}

JavaScript

function handleReportingResults(results) {
  if (!results.code) {
    outputToPage('Query Success');
    for( var i = 0, report; report = results.reports[ i ]; ++i )
    {
      output.push('<h3>All Rows Of Data</h3>');
      if (report.data.rows && report.data.rows.length) {
        var table = ['<table>'];

        // Put headers in table.
        table.push('<tr><th>', report.columnHeader.dimensions.join('</th><th>'), '</th>');
        table.push('<th>Date range #</th>');

        for (var i=0, header; header = report.columnHeader.metricHeader.metricHeaderEntries[i]; ++i) {
          table.push('<th>', header.name, '</th>');
        }

        table.push('</tr>');

        // Put cells in table.
        for (var rowIndex=0, row; row = report.data.rows[rowIndex]; ++rowIndex) {
          for(var dateRangeIndex=0, dateRange; dateRange = row.metrics[dateRangeIndex]; ++dateRangeIndex) {
            // Put dimension values
            table.push('<tr><td>', row.dimensions.join('</td><td>'), '</td>');
            // Put metric values for the current date range
            table.push('<td>', dateRangeIndex, '</td><td>', dateRange.values.join('</td><td>'), '</td></tr>');
          }
        }
        table.push('</table>');

        output.push(table.join(''));
      } else {
        output.push('<p>No rows found.</p>');
      }
    }
    outputToPage(output.join(''));

  } else {
    outputToPage('There was an error: ' + results.message);
  }
}

Salida JSON

{
  "reports": [
    {
      "columnHeader": {
        "dimensions": [
          "ga:browser"
        ],
        "metricHeader": {
          "metricHeaderEntries": [
            {
              "name": "ga:sessions",
              "type": "INTEGER"
            }
          ]
        }
      },
      "data": {
        "rows": [
          {
            "dimensions": [
              "Firefox"
            ],
            "metrics": [
              {
                "values": [
                  "2161"
                ]
              },
              {
                "values": [
                  "2171"
                ]
              }
            ]
          },
          {
            "dimensions": [
              "Internet Explorer"
            ],
            "metrics": [
              {
                "values": [
                  "1705"
                ]
              },
              {
                "values": [
                  "2019"
                ]
              }
            ]
          },
        ],
        ...
      }
    }
  ]
}

Expresiones de métricas

Los parámetros de métricas repetidos pueden incluir cualquiera de las métricas existentes, pero también puedes crear una métrica calculada personalizada combinando las métricas existentes para formar una nueva expresión de métricas. El ejemplo siguiente es una operación de división, por lo que se ha utilizado la métrica formattingType con el valor FLOAT y se ha utilizado el parámetro alias:

Java

// Create the Metrics object.
Metric metricExpression = new Metric()
    .setExpression("ga:goal1Completions/ga:goal1Starts")
    .setFormattingType("FLOAT")
    .setAlias("Metric Expression");

Python

# Create the Metrics object.
metric_expression = {
  'expression': 'ga:goal1Completions/ga:goal1Starts',
  'formattingType': 'FLOAT',
  'alias': 'Metric Expression'
}

PHP

// Create the Metrics object.
$metric_expression = new Google_Service_AnalyticsReporting_Metric();
$metric_expression->setExpression("ga:goal1Completions/ga:goal1Starts");
$metric_expression->setFormattingType("FLOAT");
$metric_expression->setAlias("Metric Expression");

JavaScript

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
    {

      ...

      "metrics":[
        {
          "expression":"ga:goal1Completions/ga:goal1Starts",
          "formattingType":"FLOAT",
         "alias":"Metric Expression"
       }]
    }
  ]
} ).execute(handleReportingResults)

JSON

"metrics":[
{
  "expression":"ga:goal1Completions/ga:goal1Starts",
  "formattingType":"FLOAT",
  "alias":"Metric Expression"
}]

Agrupaciones de histograma

La versión 4 de la API también permite definir un conjunto propio de agrupaciones de histograma personalizadas, lo que evita tener que realizar trabajos costosos de procesamiento de datos en el cliente. A continuación se ofrece un ejemplo de dimensiones agrupadas. Observa que también se incluye el parámetro orderBy, el cual clasificará las dimensiones agrupadas en el orden correcto:

Java

// Create the Dimensions object.
Dimension buckets = new Dimension()
    .setName("ga:sessionCount")
    .setHistogramBuckets(Arrays.asList(1L,10L,100L,200L,300L,400L));

// Create the Ordering.
OrderBy ordering = new OrderBy()
    .setOrderType("HISTOGRAM_BUCKET")
    .setFieldName("ga:sessionCount");

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
    "dateRanges": [
        {
            "endDate": "2015-11-30",
            "startDate": "2015-11-01"
        }
    ],
    "metrics": [
        {
            "expression": "ga:users"
        }
    ],
    "viewId": "XXXX",
    "dimensions":[
    {
      "name":"ga:sessionCount",
      "histogramBuckets":["1","10","100","200","400"]
    }],
    "orderBys":[
    {
      "fieldName":"ga:sessionCount",
      "orderType":"HISTOGRAM_BUCKET"
    }],
  }]
  }
).execute()

PHP

// Create the Dimensions object.
$buckets = new Google_Service_AnalyticsReporting_Dimension();
$buckets->setName("ga:sessionCount");
$buckets->setHistogramBuckets(array(1,10,100,200,300,400));

// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("HISTOGRAM_BUCKET");
$ordering->setFieldName("ga:sessionCount");

JavaScript

 api.client.analyticsreporting.reports.batchGet( {
   "reportRequests":[
     {
       "dateRanges": [
         {
           "endDate": "2015-11-30",
           "startDate": "2015-11-01"
         }
       ],
       "metrics": [
         {
            "expression": "ga:users"
         }
       ],
      "viewId": "XXXX",
      "dimensions":[
      {
        "name":"ga:sessionCount",
        "histogramBuckets":["1","10","100","200","400"]
      }],
      "orderBys":[
      {
        "fieldName":"ga:sessionCount",
        "orderType":"HISTOGRAM_BUCKET"
      }],
     }]
 } ).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "dateRanges": [
        {
            "endDate": "2014-11-30",
            "startDate": "2014-11-01"
        }
    ],
    "metrics": [
        {
            "expression": "ga:users"
        }
    ],
    "viewId": "XXXX",
    "dimensions":[
    {
      "name":"ga:sessionCount",
      "histogramBuckets":["1","10","100","200","400"]
    }],
    "orderBys":[
    {
      "fieldName":"ga:sessionCount",
      "orderType":"HISTOGRAM_BUCKET"
    }],
  }]
}

Respuesta JSON

{
    "reports": [
        {
            "columnHeader": {
                "dimensions": [
                    "ga:sessionCount"
                ],
                "metricHeader": {
                    "metricHeaderEntries": [
                        {
                            "name": "ga:users",
                            "type": "INTEGER"
                        }
                    ]
                }
            },
            "data": {
                "isDataGolden": true,
                "maximums": [
                    {
                        "values": [
                            "94"
                        ]
                    }
                ],
                "minimums": [
                    {
                        "values": [
                            "2"
                        ]
                    }
                ],
                "rowCount": 5,
                "rows": [
                    {
                        "dimensions": [
                            "1-9"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "94"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "10-99"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "21"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "100-199"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "57"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "200-399"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "20"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "400+"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "2"
                                ]
                            }
                        ]
                    }
                ],
                "totals": [
                    {
                        "values": [
                            "194"
                        ]
                    }
                ]
            }
        }
    ]
}

Segmentos

Los segmentos se definen combinando operadores lógicos de objetos de filtro de segmentos. También es necesario agregar ga:segment a la lista de dimensiones. Puedes crear las definiciones de segmentos de forma dinámica dentro de la consulta o bien especificar un ID de un segmento integrado o personalizado que ya tengas. A continuación se ofrece un ejemplo de definición de segmento dinámica:

Java

private static void segmentRequest(Analyticsreporting analyticsreporting) throws IOException {

  // Create the DateRange object.
  DateRange dateRange = new DateRange();
  dateRange.setStartDate("2015-06-15");
  dateRange.setEndDate("2015-06-30");

  // Create the Metrics object.
  Metric sessions = new Metric()
      .setExpression("ga:sessions")
      .setAlias("sessions");

  //Create the browser dimension.
  Dimension browser = new Dimension()
      .setName("ga:browser");

  // Create the segment dimension.
  Dimension segmentDimensions = new Dimension()
      .setName("ga:segment");

  // Create Dimension Filter.
  SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter()
      .setDimensionName("ga:browser")
      .setOperator("EXACT")
      .setExpressions(Arrays.asList("Safari"));

  // Create Segment Filter Clause.
  SegmentFilterClause segmentFilterClause = new SegmentFilterClause()
      .setDimensionFilter(dimensionFilter);

  // Create the Or Filters for Segment.
  OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment()
      .setSegmentFilterClauses(Arrays.asList(segmentFilterClause));

  // Create the Simple Segment.
  SimpleSegment simpleSegment = new SimpleSegment()
      .setOrFiltersForSegment(Arrays.asList(orFiltersForSegment));

  // Create the Segment Filters.
  SegmentFilter segmentFilter = new SegmentFilter()
      .setSimpleSegment(simpleSegment);

  // Create the Segment Definition.
  SegmentDefinition segmentDefinition = new SegmentDefinition()
      .setSegmentFilters(Arrays.asList(segmentFilter));

  // Create the Dynamic Segment.
  DynamicSegment dynamicSegment = new DynamicSegment()
      .setSessionSegment(segmentDefinition)
      .setName("Sessions with Safari browser");

  // Create the Segments object.
  Segment segment = new Segment()
      .setDynamicSegment(dynamicSegment);

  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest()
      .setViewId("XXXX")
      .setDateRanges(Arrays.asList(dateRange))
      .setDimensions(Arrays.asList(browser, segmentDimensions))
      .setSegments(Arrays.asList(segment))
      .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest()
      .setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport)
      .execute();

  printResults(response.getReports());
}

Python

  response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}).execute()

PHP

function segmentRequest(&$analyticsreporting) {

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  //Create the browser dimension.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  // Create the segment dimension.
  $segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
  $segmentDimensions->setName("ga:segment");

  // Create Dimension Filter.
  $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  $dimensionFilter->setDimensionName("ga:browser");
  $dimensionFilter->setOperator("EXACT");
  $dimensionFilter->setExpressions(array("Safari"));

  // Create Segment Filter Clause.
  $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
  $segmentFilterClause->setDimensionFilter($dimensionFilter);

  // Create the Or Filters for Segment.
  $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
  $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

  // Create the Simple Segment.
  $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
  $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

  // Create the Segment Filters.
  $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
  $segmentFilter->setSimpleSegment($simpleSegment);

  // Create the Segment Definition.
  $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
  $segmentDefinition->setSegmentFilters(array($segmentFilter));

  // Create the Dynamic Segment.
  $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
  $dynamicSegment->setSessionSegment($segmentDefinition);
  $dynamicSegment->setName("Sessions with Safari browser");

  // Create the Segments object.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setDynamicSegment($dynamicSegment);

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

JavaScript

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}

Como hemos mencionado, en lugar de construir una definición de segmento dinámica se puede especificar un ID de segmento predefinido mediante el campo segmentId de la definición de segmento. En el ejemplo siguiente se crea un segmento de usuarios recurrentes.

Java

  // Create the Segments object for returning users.
  Segment segment = new Segment()
      .setSegmentId("gaid::-3");

  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest()
      .setViewId("XXXX")
      .setDateRanges(Arrays.asList(dateRange))
      .setDimensions(Arrays.asList(browser, segmentDimensions))
      .setSegments(Arrays.asList(segment))
      .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest()
      .setReportRequests(Arrays.asList(request));

Python

  response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}).execute()

PHP

  // Create the Segments object for returning users.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setSegmentId("gaid::-3");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

JavaScript

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}

Se puede obtener una lista de los segmentos disponibles junto con su correspondiente descripción e ID usando el método list de la versión 3 de la API de administración de Analytics.

Varios segmentos

La versión 4 de la API de informes también permite incluir varios segmentos dentro de la definición de ReportRequest. A continuación se muestra una consulta simple con varios segmentos:

Java

private static Segment buildSimpleSegment(
    String segmentName, String dimension, String dimensionFilterExpression) {
  // Create Dimension Filter.
  SegmentDimensionFilter dimensionFilter =
      new SegmentDimensionFilter()
          .setDimensionName(dimension)
          .setOperator("EXACT")
          .setExpressions(Arrays.asList(dimensionFilterExpression));

  // Create Segment Filter Clause.
  SegmentFilterClause segmentFilterClause =
      new SegmentFilterClause().setDimensionFilter(dimensionFilter);

  // Create the Or Filters for Segment.
  OrFiltersForSegment orFiltersForSegment =
      new OrFiltersForSegment().setSegmentFilterClauses(Arrays.asList(segmentFilterClause));

  // Create the Simple Segment.
  SimpleSegment simpleSegment =
      new SimpleSegment().setOrFiltersForSegment(Arrays.asList(orFiltersForSegment));

  // Create the Segment Filters.
  SegmentFilter segmentFilter = new SegmentFilter().setSimpleSegment(simpleSegment);

  // Create the Segment Definition.
  SegmentDefinition segmentDefinition =
      new SegmentDefinition().setSegmentFilters(Arrays.asList(segmentFilter));

  // Create the Dynamic Segment.
  DynamicSegment dynamicSegment =
      new DynamicSegment().setSessionSegment(segmentDefinition).setName(segmentName);

  // Create the Segments object.
  Segment segment = new Segment().setDynamicSegment(dynamicSegment);
  return segment;
}

private static void multipleSegmentsRequest(Analyticsreporting analyticsreporting) throws IOException {
  // Create the DateRange object.
  DateRange dateRange = new DateRange();
  dateRange.setStartDate("2015-06-15");
  dateRange.setEndDate("2015-06-30");

  // Create the Metrics object.
  Metric sessions = new Metric().setExpression("ga:sessions").setAlias("sessions");

  Dimension browser = new Dimension().setName("ga:browser");

  Dimension segmentDimensions = new Dimension().setName("ga:segment");

  Segment browserSegment =
      buildSimpleSegment("Sessions with Safari browser", "ga:browser", "Safari");

  Segment countrySegment =
      buildSimpleSegment("Sessions from United States", "ga:country", "United States");

  // Create the ReportRequest object.
  ReportRequest request =
      new ReportRequest()
          .setViewId("XXXX")
          .setDateRanges(Arrays.asList(dateRange))
          .setDimensions(Arrays.asList(browser, segmentDimensions))
          .setSegments(Arrays.asList(browserSegment, countrySegment))
          .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest().setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

  printResults(response.getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(
    body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
      {
        "endDate":"2015-06-30",
        "startDate":"2015-06-15"
      }],
      "dimensions":[
      {
        "name":"ga:browser"
      },
      {
        "name":"ga:segment"
      }],
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      }],
      "segments":[
      {
        "dynamicSegment":
        {
          "name":"Safari",
          "sessionSegment":
          {
            "segmentFilters":[
            {
              "simpleSegment":
              {
                "orFiltersForSegment":[
                {
                  "segmentFilterClauses":[
                  {
                    "dimensionFilter":
                    {
                      "dimensionName":"ga:browser",
                      "expressions":["Safari"],
                      "operator":"EXACT"
                    }
                  }]
                }]
              }
            }]
          }
        }
      },
      {
        "dynamicSegment":
        {
          "name":"United States",
          "sessionSegment":
          {
            "segmentFilters":[
            {
              "simpleSegment":
              {
                "orFiltersForSegment":[
                {
                  "segmentFilterClauses":[
                  {
                    "dimensionFilter":
                    {
                      "dimensionName":"ga:country",
                      "expressions":["United States"],
                      "operator":"EXACT"
                    }
                  }]
                }]
              }
            }]
          }
        }
      }]
    }]
}).execute()

PHP

function  buildSimpleSegment($segmentName, $dimension, $dimensionFilterExpression) {
  // Create the segment dimension.
  $segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
  $segmentDimensions->setName("ga:segment");

  // Create Dimension Filter.
  $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  $dimensionFilter->setDimensionName($dimension);
  $dimensionFilter->setOperator("EXACT");
  $dimensionFilter->setExpressions(array($dimensionFilterExpression));

  // Create Segment Filter Clause.
  $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
  $segmentFilterClause->setDimensionFilter($dimensionFilter);

  // Create the Or Filters for Segment.
  $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
  $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

  // Create the Simple Segment.
  $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
  $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

  // Create the Segment Filters.
  $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
  $segmentFilter->setSimpleSegment($simpleSegment);

  // Create the Segment Definition.
  $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
  $segmentDefinition->setSegmentFilters(array($segmentFilter));

  // Create the Dynamic Segment.
  $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
  $dynamicSegment->setSessionSegment($segmentDefinition);
  $dynamicSegment->setName($segmentName);

  // Create the Segments object.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setDynamicSegment($dynamicSegment);
  return $segment;
}

function multipleSegmentsRequest(&$analyticsreporting) {

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  //Create the browser dimension.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setMetrics(array($sessions));

  // Specifying multiple segments
  $browserSegment = buildSimpleSegment("Sessions with Safari browser", "ga:browser", "Safari");
  $countrySegment = buildSimpleSegment("Sessions from United States", "ga:country", "United States");
  $request->setSegments(array($browserSegment, $countrySegment));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

JavaScript

 gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:segment"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name":"Safari",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "expressions":["Safari"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    },
    {
      "dynamicSegment":
      {
        "name":"United States",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:country",
                    "expressions":["United States"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    }]
  }]
 }).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:segment"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name":"Safari",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "expressions":["Safari"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    },
    {
      "dynamicSegment":
      {
        "name":"United States",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:country",
                    "expressions":["United States"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    }]
  }]
}

Tablas dinámicas

La versión 4 de la API de informes admite las tablas dinámicas. Las solicitudes que incluyen una tabla dinámica reorganizan la información de la tabla desplazando los datos a otra dimensión. En la referencia de la API encontrarás más información sobre las tablas dinámicas.

Java

private static void pivotRequest(Analyticsreporting analyticsreporting) throws IOException {

    // Create the DateRange object.
    DateRange dateRange = new DateRange();
    dateRange.setStartDate("2015-06-15");
    dateRange.setEndDate("2015-06-30");

    // Create the Metric objects.
    Metric sessions = new Metric()
        .setExpression("ga:sessions")
        .setAlias("sessions");
    Metric pageviews = new Metric()
        .setExpression("ga:pageviews")
        .setAlias("pageviews");

    // Create the Dimension objects.
    Dimension browser = new Dimension()
        .setName("ga:browser");
    Dimension campaign = new Dimension()
        .setName("ga:campaign");
    Dimension age = new Dimension()
        .setName("ga:userAgeBracket");

    // Create the Pivot object.
    Pivot pivot = new Pivot()
        .setDimensions(Arrays.asList(age))
        .setMaxGroupCount(3)
        .setStartGroup(0)
        .setMetrics(Arrays.asList(sessions, pageviews));

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
        .setViewId("XXXX")
        .setDateRanges(Arrays.asList(dateRange))
        .setDimensions(Arrays.asList(browser, campaign))
        .setPivots(Arrays.asList(pivot))
        .setMetrics(Arrays.asList(sessions));

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest()
        .setReportRequests(Arrays.asList(request));

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.reports().batchGet(getReport)
        .execute();

    printResults(response.getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(
  body:{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}).execute()

PHP

function pivotRequest(&$analyticsreporting) {
  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metric objects.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  $pageviews = new Google_Service_AnalyticsReporting_Metric();
  $pageviews->setExpression("ga:pageviews");
  $pageviews->setAlias("pageviews");

  // Create the Dimension objects.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  $campaign = new Google_Service_AnalyticsReporting_Dimension();
  $campaign->setName("ga:campaign");

  $age = new Google_Service_AnalyticsReporting_Dimension();
  $age->setName("ga:userAgeBracket");

  // Create the Pivot object.
  $pivot = new Google_Service_AnalyticsReporting_Pivot();
  $pivot->setDimensions(array($age));
  $pivot->setMaxGroupCount(3);
  $pivot->setStartGroup(0);
  $pivot->setMetrics(array($sessions, $pageviews));

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $campaign));
  $request->setPivots(array($pivot));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array($request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

JavaScript

gapi.client.analyticsreporting.reports.batchGet({
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}).execute(handleReportingResults)

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}

Cohortes

Las cohortes son una nueva función de la versión 4 de la API de informes que permite generar informes de grupos de usuarios que comparten una característica común. En la guía de desarrollo y en la referencia de la API encontrarás más información sobre las cohortes.

Java

private static void cohortRequest(Analyticsreporting analyticsreporting) throws IOException {
  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest().setViewId("XXXX");

  // Set the cohort dimensions
  request.setDimensions(Arrays.asList(
      new Dimension().setName("ga:cohort"), new Dimension().setName("ga:cohortNthWeek")));
  // Set the cohort metrics
  request.setMetrics(Arrays.asList(
      new Metric().setExpression("ga:cohortTotalUsersWithLifetimeCriteria"),
      new Metric().setExpression("ga:cohortRevenuePerUser")));

  // Create the first cohort
  Cohort cohort1 =
      new Cohort()
          .setName("cohort_1")
          .setType("FIRST_VISIT_DATE")
          .setDateRange(new DateRange().setStartDate("2015-08-01").setEndDate("2015-09-01"));

  // Create the second cohort which only differs from the first one by the date range
  Cohort cohort2 =
      new Cohort()
          .setName("cohort21")
          .setType("FIRST_VISIT_DATE")
          .setDateRange(new DateRange().setStartDate("2015-07-01").setEndDate("2015-08-01"));

  // Create the cohort group
  CohortGroup cohortGroup = new CohortGroup();
  cohortGroup.setCohorts(Arrays.asList(cohort1, cohort2));
  cohortGroup.setLifetimeValue(true);

  request.setCohortGroup(cohortGroup);

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest().setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

  printResults(response.getReports());
}

PHP

function cohortRequest(&$analyticsreporting) {
    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId("XXXX");

    $cohortDimension = new Google_Service_AnalyticsReporting_Dimension();
    $cohortDimension->setName("ga:cohort");

    $cohortNthWeekDimension = new Google_Service_AnalyticsReporting_Dimension();
    $cohortNthWeekDimension->setName("ga:cohortNthWeek");

    // Set the cohort dimensions
    $request->setDimensions(array($cohortDimension, $cohortNthWeekDimension));

    $cohortTotalUsersMetric = new Google_Service_AnalyticsReporting_Metric();
    $cohortTotalUsersMetric->setExpression("ga:cohortTotalUsersWithLifetimeCriteria");

    $cohortRevenuePerUserMetric = new Google_Service_AnalyticsReporting_Metric();
    $cohortRevenuePerUserMetric->setExpression("ga:cohortRevenuePerUser");

    // Set the cohort metrics
    $request->setMetrics(array($cohortTotalUsersMetric, $cohortRevenuePerUserMetric));

    $dateRange1 = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange1->setStartDate("2015-08-01");
    $dateRange1->setEndDate("2015-09-01");

    // Create the first cohort
    $cohort1 = new Google_Service_AnalyticsReporting_Cohort();
    $cohort1->setName("cohort_1");
    $cohort1->setType("FIRST_VISIT_DATE");
    $cohort1->setDateRange($dateRange1);

    $dateRange2 = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange2->setStartDate("2015-07-01");
    $dateRange2->setEndDate("2015-08-01");

    // Create the second cohort which only differs from the first one by the date range
    $cohort2 = new Google_Service_AnalyticsReporting_Cohort();
    $cohort2->setName("cohort_2");
    $cohort2->setType("FIRST_VISIT_DATE");
    $cohort2->setDateRange($dateRange2);

    // Create the cohort group
    $cohortGroup = new Google_Service_AnalyticsReporting_CohortGroup();
    $cohortGroup->setCohorts(array($cohort1, $cohort2));
    $cohortGroup->setLifetimeValue(true);

    $request->setCohortGroup($cohortGroup);

    // Create the GetReportsRequest object.
    $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $getReport->setReportRequests(array($request));

    // Call the batchGet method.
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array($request) );
    $response = $analyticsreporting->reports->batchGet( $body );

    printResults($response->getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(body={
    "reportRequests": [
        {
            "viewId": "XXXX",
            "dimensions": [
                {"name": "ga:cohort"},
                {"name": "ga:cohortNthWeek"}],
            "metrics": [
                {"expression": "ga:cohortTotalUsersWithLifetimeCriteria"},
                {"expression": "ga:cohortRevenuePerUser"}
            ],
            "cohortGroup": {
                "cohorts": [{
                    "name": "cohort 1",
                    "type": "FIRST_VISIT_DATE",
                    "dateRange": {
                        "startDate": "2015-08-01",
                        "endDate": "2015-09-01"
                    }
                },
                            {
                                "name": "cohort 2",
                                "type": "FIRST_VISIT_DATE",
                                "dateRange": {
                                    "startDate": "2015-07-01",
                                    "end_date": "2015-08-01"
                                }
                            }],
                "lifetimeValue": True
            }
        }]
}).execute()

JSON

{
  "reportRequests": [
    {
        "viewId": "XXXX",
        "dimensions": [
            {"name": "ga:cohort" },
            {"name": "ga:cohortNthWeek" }],
        "metrics": [
            {"expression": "ga:cohortTotalUsersWithLifetimeCriteria"},
            {"expression": "ga:cohortRevenuePerUser"}
        ],
        "cohortGroup": {
            "cohorts": [{
                "name": "cohort 1",
                "type": "FIRST_VISIT_DATE",
                "dateRange": {
                    "startDate": "2015-08-01",
                    "endDate": "2015-09-01"
                }
            },
            {
                "name": "cohort 2",
                "type": "FIRST_VISIT_DATE",
                "dateRange": {
                    "startDate": "2015-07-01",
                    "end_date": "2015-08-01"
                }
            }],
           "lifetimeValue": True
        }
    }]
}