Samples

This article provides samples of the Google Analytics Reporting API v4 features.

Dimensions and Metrics

Below is a simple request with just a few dimensions and metrics. See the Dimensions and Metrics Explorer For the complete set of dimensions and metrics available. The dimensions and metrics are configurable repeated objects passed in the post body.

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)

C#

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };

// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange>() { dateRange },
    Dimensions = new List<Dimension>() { browser },
    Metrics = new List<Metric>() { sessions }
};

List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

JSON

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

Multiple Date Ranges

Below is an example with multiple date ranges:

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)

C#

// Create the DateRange object.
DateRange march = new DateRange() { StartDate = "2015-03-01", EndDate = "2015-03-31" };

DateRange january = new DateRange() { StartDate = "2015-01-01", EndDate = "2015-01-31" };

// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };

// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange>() { march, january },
    Dimensions = new List<Dimension>() { browser },
    Metrics = new List<Metric>() { sessions }
};

List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

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"
    }]
  }]
}

When parsing the response of a request with multiple date ranges the results are returned as an array of 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($metrics) && $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}

JavaScript

function handleReportingResults(response) {
  if (!response.code) {
    outputToPage('Query Success');
    for( var i = 0, report; report = response.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: ' + response.message);
  }
}

C#

public static void printResults(List<Report> reports)
{
    foreach (Report report in reports)
    {
        ColumnHeader header = report.ColumnHeader;
        List<string> dimensionHeaders = (List<string>)header.Dimensions;

        List<MetricHeaderEntry> metricHeaders = (List<MetricHeaderEntry>)header.MetricHeader.MetricHeaderEntries;
        List<ReportRow> rows = (List<ReportRow>)report.Data.Rows;

        foreach (ReportRow row in rows)
        {
            List<string> dimensions = (List<string>)row.Dimensions;
            List<DateRangeValues> metrics = (List<DateRangeValues>)row.Metrics;

            for (int i = 0; i < dimensionHeaders.Count() && i < dimensions.Count(); i++)
            {
                Console.WriteLine(dimensionHeaders[i] + ": " + dimensions[i]);
            }

            for (int j = 0; j < metrics.Count(); j++)
            {
                Console.WriteLine("Date Range (" + j + "): ");
                DateRangeValues values = metrics[j];
                for (int k = 0; k < values.Values.Count() && k < metricHeaders.Count(); k++)
                {
                    Console.WriteLine(metricHeaders[k].Name + ": " + values.Values[k]);
                }
            }
        }
    }
}

Output 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"
                ]
              }
            ]
          },
        ],
        ...
      }
    }
  ]
}

Metric Expressions

The repeated metrics parameters can take any of the existing metrics but you can also create a custom calculated metric, by combining existing metrics into a new metrics expression. Notice because the below sample is a division operation, I also need to set the formattingType to be FLOAT; I am also making use of the alias parameter:

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)

C#

// Create the Metrics object.
Metric metricExpression = new Metric
{
    Expression = "ga:goal1Completions/ga:goal1Starts",
    FormattingType = "FLOAT",
    Alias = "Metric Expression"
};

JSON

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

Histogram Buckets

The API v4 also allows you to define your own set of custom histogram buckets saving you from doing expensive data processing on the client side. Below is an example of bucketed dimensions. Note there is also orderBy parameter which will sort the bucketed dimensions in the correct order:

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

 gapi.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)

C#

// Create the Dimensions object.
Dimension buckets = new Dimension
{
    Name = "ga:sessionCount",
    HistogramBuckets = (IList<long?>)new List<long> { 1L, 10L, 100L, 200L, 300L, 400L }
};

// Create the Ordering.
OrderBy ordering = new OrderBy()
{
    OrderType = "HISTOGRAM_BUCKET",
    FieldName = "ga:sessionCount"
};

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"
    }],
  }]
}

JSON Response

{
    "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"
                        ]
                    }
                ]
            }
        }
    ]
}

Segments

The segments are defined by combining logical operators of segment filter objects. You also you notice that it is necessary to add ga:segment to the list of dimensions. Segment definitions can be either constructed dynamically inside the query, or you can specify an id of an existing built-in/custom segment. Below is an example of using a dynamic segment definition:

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)

C#

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

//Create the browser dimension.
Dimension browser = new Dimension() { Name = "ga:browser" };

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

// Create Dimension Filter.
SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter() { DimensionName = "ga:browser", Operator__ = "EXACT", Expressions = new List<string> { "Safari" } };

// Create Segment Filter Clause.
SegmentFilterClause segmentFilterClause = new SegmentFilterClause() { DimensionFilter = dimensionFilter };

// Create the Or Filters for Segment.
OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment() { SegmentFilterClauses = new List<SegmentFilterClause> { segmentFilterClause } };

// Create the Simple Segment.
SimpleSegment simpleSegment = new SimpleSegment() { OrFiltersForSegment = new List<OrFiltersForSegment> { orFiltersForSegment } };

// Create the Segment Filters.
SegmentFilter segmentFilter = new SegmentFilter() { SimpleSegment = simpleSegment };

// Create the Segment Definition.
SegmentDefinition segmentDefinition = new SegmentDefinition() { SegmentFilters = new List<SegmentFilter> { segmentFilter } };

// Create the Dynamic Segment.
DynamicSegment dynamicSegment = new DynamicSegment() { SessionSegment = segmentDefinition, Name = "Sessions with Safari browser" };

// Create the Segments object.
Segment segment = new Segment() { DynamicSegment = dynamicSegment };

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange> { dateRange },
    Dimensions = new List<Dimension> { browser, segmentDimensions },
    Segments = new List<Segment> { segment },
    Metrics = new List<Metric> { sessions }
};

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

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"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}

As mentioned above, instead of constructing a dynamic segment definition, it is possible to specify a predefined segment id using segmentId field of Segment definition. The example below creates a segment for returning users.

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)

C#

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

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

//Create the browser dimension.
Dimension browser = new Dimension() { Name = "ga:browser" };

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

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange> { dateRange },
    Dimensions = new List<Dimension> { browser, segmentDimensions },
    Segments = new List<Segment> { segment },
    Metrics = new List<Metric> { sessions }
};

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

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"
    }]
  }]
}

A list of available segments along with their description and segment id can be obtained using list method of Analytics Management API v3.

Multiple Segments

The Reporting API v4 also supports multiple segments inside the ReportRequest definition. Below is a simple query with multiple segments:

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)

C#

public static Segment buildSimpleSegment(String segmentName, String dimension, String dimensionFilterExpression)
{
    // Create Dimension Filter.
    SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter() { DimensionName = dimension, Operator__ = "EXACT", Expressions = new List<string> { dimensionFilterExpression } };

    // Create Segment Filter Clause.
    SegmentFilterClause segmentFilterClause = new SegmentFilterClause() { DimensionFilter = dimensionFilter };

    // Create the Or Filters for Segment.
    OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment() { SegmentFilterClauses = new List<SegmentFilterClause> { segmentFilterClause } };

    // Create the Simple Segment.
    SimpleSegment simpleSegment = new SimpleSegment() { OrFiltersForSegment = new List<OrFiltersForSegment> { orFiltersForSegment } };

    // Create the Segment Filters.
    SegmentFilter segmentFilter = new SegmentFilter() { SimpleSegment = simpleSegment };

    // Create the Segment Definition.
    SegmentDefinition segmentDefinition = new SegmentDefinition() { SegmentFilters = new List<SegmentFilter> { segmentFilter } };

    // Create the Dynamic Segment.
    DynamicSegment dynamicSegment = new DynamicSegment() { SessionSegment = segmentDefinition, Name = segmentName };

    // Create the Segments object.
    Segment segment = new Segment() { DynamicSegment = dynamicSegment };

    return segment;
}

public static void multipleSegmentsRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

    // Create the Metrics object.
    Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

    Dimension browser = new Dimension() { Name = "ga:browser" };

    Dimension segmentDimensions = new Dimension() { Name = "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()
    {
        ViewId = "XXXX",
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { browser, segmentDimensions },
        Segments = new List<Segment> { browserSegment, countrySegment },
        Metrics = new List<Metric> { sessions }
    };

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

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"
                  }
                }]
              }]
            }
          }]
        }
      }
    }]
  }]
}

Pivots

The Reporting API v4 has support for pivots. Requests with a pivot will rearrange the information in the table by pivoting your data on a second dimension. See more information on Pivots in the API reference.

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)

C#

public static void pivotRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

    // Create the Metric objects.
    Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

    Metric pageviews = new Metric() { Expression = "ga:pageviews", Alias = "pageviews" };

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

    // Create the Pivot object.
    Pivot pivot = new Pivot() { Dimensions = new List<Dimension> { age }, MaxGroupCount = 3, StartGroup = 0, Metrics = new List<Metric> { sessions, pageviews } };

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
    {
        ViewId = "XXXX",
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { browser, campaign },
        Pivots = new List<Pivot> { pivot },
        Metrics = new List<Metric> { sessions }
    };

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

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"
      }]
    }]
  }]
}

Cohorts

Cohorts are the new feature of the Reporting API v4 that allows for generating reports on groups of users who share a common characteristic. See more on Cohorts in the development guide and the API reference

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

C#

private static void cohortRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest() { ViewId = "XXXX" };

    // Set the cohort dimensions
    request.Dimensions  = new List<Dimension> { new Dimension() { Name = "ga:cohort" }, new Dimension() { Name = "ga:cohortNthWeek" } } ;

    // Set the cohort metrics
    request.Metrics = new List<Metric> { new Metric() { Expression = "ga:cohortTotalUsersWithLifetimeCriteria" }, new Metric() { Expression = "ga:cohortRevenuePerUser" } };

    // Create the first cohort
    Cohort cohort1 =  new Cohort() { Name = "cohort_1", Type = "FIRST_VISIT_DATE", DateRange = new DateRange() { StartDate = "2015-08-01", EndDate = "2015-09-01" } };

    // Create the second cohort which only differs from the first one by the date range
    Cohort cohort2 = new Cohort() { Name = "cohort21", Type = "FIRST_VISIT_DATE", DateRange = new DateRange() { StartDate = "2015-07-01", EndDate = "2015-08-01" } };

    // Create the cohort group
    CohortGroup cohortGroup = new CohortGroup();
    cohortGroup.Cohorts = new List<Cohort> { cohort1, cohort2 };
    cohortGroup.LifetimeValue = true;
    request.CohortGroup = cohortGroup;

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

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