Core Reporting API - Reference Guide

This document provides the complete reference for both query and response for the Core Reporting API version 3.0.

Introduction

You query the Core Reporting API for Google Analytics report data. Each query requires a view (profile) ID, a start and end date, and at least one metric. You may also supply additional query parameters such as dimensions, filters, and segments to refine your query. See the Overview Guide to understand how all these concepts work together.

Request

The API provides a single method to request data:

analytics.data.ga.get()

This method is exposed in various client libraries and has language specific interfaces to set the query parameters.

The API also can be queried as a REST-ful endpoint:

Authorization: Bearer {oauth2-token}

GET https://www.googleapis.com/analytics/v3/data/ga
  ?ids=ga:12345
  &start-date=2008-10-01
  &end-date=2008-10-31
  &metrics=ga:sessions,ga:bounces

Each URL query parameter specifies an API query parameter that must be URL encoded.

Query Parameters Summary

The following table summarizes all the query parameters accepted by the Core reporting API. Click each parameter name for a detailed description.

Name Value Required Summary
ids string yes The unique table ID of the form ga:XXXX, where XXXX is the Analytics view (profile) ID for which the query will retrieve the data.
start-date string yes Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer).
end-date string yes End date for fetching Analytics data. Request can specify an end date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or NdaysAgo where N is a positive integer).
metrics string yes A list of comma-separated metrics, such as ga:sessions,ga:bounces.
dimensions string no A list of comma-separated dimensions for your Analytics data, such as ga:browser,ga:city.
sort string no A list of comma-separated dimensions and metrics indicating the sorting order and sorting direction for the returned data.
filters string no Dimension or metric filters that restrict the data returned for your request.
segment string no Segments the data returned for your request.
samplingLevel string no The desired sampling level. Allowed Values:
  • DEFAULT — Returns response with a sample size that balances speed and accuracy.
  • FASTER — Returns a fast response with a smaller sample size.
  • HIGHER_PRECISION — Returns a more accurate response using a large sample size, but this may result in the response being slower.
include-empty-rows boolean no Defaults to true; if set to false, rows where all metric values are zero will be omitted from the response.
start-index integer no The first row of data to retrieve, starting at 1. Use this parameter as a pagination mechanism along with the max-results parameter.
max-results integer no The maximum number of rows to include in the response.
output string no The desired output type for the Analytics data returned in the response. Acceptable values are json and dataTable. Default: json.
fields string no Selector specifying a subset of fields to include in the response.
prettyPrint string no Returns response with indentations and line breaks. Default false.
userIp string no Specifies IP address of the end user for whom the API call is being made. Used to cap usage per IP.
quotaUser string no Alternative to userIp in cases when the user's IP address is unknown.
access_token string no One possible way to provide an OAuth 2.0 token.
callback string no Name of the JavaScript callback function that handles the response. Used in JavaScript JSON-P requests.
key string no Used for OAuth 1.0a authorization to specify your application to get quota. For example: key=AldefliuhSFADSfasdfasdfASdf.

Query Parameter Details

ids

ids=ga:12345
Required.
The unique ID used to retrieve the Analytics data. This ID is the concatenation of the namespace ga: with the Analytics view (profile) ID. You can retrieve the view (profile) ID by using the analytics.management.profiles.list method, which provides the id in the View (Profile) resource in the Google Analytics Management API.

start-date

start-date=2009-04-20
Required.
All Analytics data requests must specify a date range. If you do not include start-date and end-date parameters in the request, the server returns an error. Date values can be for a specific date by using the pattern YYYY-MM-DD or relative by using today, yesterday, or the NdaysAgo pattern. Values must match [0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo).
The earliest valid start-date is 2005-01-01. There is no upper limit restriction for a start-date.
Relative dates are always relative to the current date at the time of the query and are based on the timezone of the view (profile) specified in the query.

Example date range for the last 7 days (starting yesterday) using relative dates:

  &start-date=7daysAgo
  &end-date=yesterday

end-date

end-date=2009-05-20
Required.
All Analytics data requests must specify a date range. If you do not include start-date and end-date parameters in the request, the server returns an error. Date values can be for a specific date by using the pattern YYYY-MM-DD or relative by using today, yesterday, or the NdaysAgo pattern. Values must match [0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo).
The earliest valid end-date is 2005-01-01. There is no upper limit restriction for an end-date.
Relative dates are always relative to the current date at the time of the query and are based on the timezone of the view (profile) specified in the query.

Example date range for the last 10 days (starting today) using relative dates:

  &start-date=9daysAgo
  &end-date=today

dimensions

dimensions=ga:browser,ga:city
Optional.
The dimensions parameter breaks down metrics by common criteria; for example, by ga:browser or ga:city. While you can ask for the total number of pageviews to your site, it might be more interesting to ask for the number of pageviews broken down by browser. In this case, you'll see the number of pageviews from Firefox, Internet Explorer, Chrome, and so forth.

When using dimensions in a data request, be aware of the following constraints:

  • You can supply a maximum of 7 dimensions in any query.
  • You can not send a query composed only of dimensions: you must combine any requested dimensions with at least one metric.
  • Only certain dimensions can be queried in the same query. Use the valid combination tool in the Dimensions and Metrics Reference to see which dimensions can be used together.


metrics

metrics=ga:sessions,ga:bounces
Required.
The aggregated statistics for user activity to your site, such as clicks or pageviews. If a query has no dimensions parameter, the returned metrics provide aggregate values for the requested date range, such as overall pageviews or total bounces. However, when dimensions are requested, values are segmented by dimension value. For example, ga:pageviews requested with ga:country returns the total pageviews per country. When requesting metrics, keep in mind:
  • Any request must supply at least one metric; a request cannot consist only of dimensions.
  • You can supply a maximum of 10 metrics for any query.
  • Most combinations of metrics from multiple categories can be used together, provided no dimensions are specified.
  • A metric can be used in combination with other dimensions or metrics, but only where valid combinations apply for that metric. See the Dimensions and Metrics Reference for details.


sort

sort=ga:country,ga:browser
Optional.

A list of metrics and dimensions indicating the sorting order and sorting direction for the returned data.

  • Sorting order is specified by the left to right order of the metrics and dimensions listed.
  • Sorting direction defaults to ascending and can be changed to descending by using a minus sign (-) prefix on the requested field.

Sorting the results of a query enables you to ask different questions about your data. For example, to address the question "What are my top countries, and which browsers do they use most?" you can make a query with the following parameter. It sorts first by ga:country and then by ga:browser, both in ascending order:

sort=ga:country,ga:browser

To answer the related question "What are my top browsers, and which countries use them most?", you can make a query with the following parameter. It sorts first by ga:browser and then by ga:country, both in ascending order:
sort=ga:browser,ga:country

When using the sort parameter, keep in mind the following:

  • Sort only by dimensions or metrics values that you have used in the dimensions or metrics parameters. If your request sorts on a field that is not indicated in either the dimensions or metrics parameter, you will receive a error.
  • By default, strings are sorted in ascending alphabetical order in en-US locale.
  • Numbers are sorted in ascending numeric order by default.
  • Dates are sorted in ascending order by date by default.

filters

filters=ga:medium%3D%3Dreferral
Optional.

The filters query string parameter restricts the data returned from your request. To use the filters parameter, supply a dimension or metric on which to filter, followed by the filter expression. For example, the following query requests ga:pageviews and ga:browser for view (profile) 12134, where the ga:browser dimension starts with the string Firefox:

https://www.googleapis.com/analytics/v3/data/ga
?ids=ga:12134
&dimensions=ga:browser
&metrics=ga:pageviews
&filters=ga:browser%3D~%5EFirefox
&start-date=2007-01-01
&end-date=2007-12-31

Filtered queries restrict the rows that do (or do not) get included in the result. Each row in the result is tested against the filter: if the filter matches, the row is retained and if it doesn't match, the row is dropped.

  • URL Encoding: The Google API client libraries automatically encode the filter operators.
  • Dimension filtering: Filtering occurs before any dimensions are aggregated, so that the returned metrics represent the total for only the relevant dimensions. In the example above, the number of pageviews would be only those pageviews where Firefox is the browser.
  • Metrics filtering: Filtering on metrics occurs after the metrics are aggregated.
  • Valid combinations: You can filter for a dimension or metric that is not part of your query, provided all dimensions/metrics in the request and the filter are valid combinations. For example, you might want to query for a dated list of pageviews, filtering on a particular browser. See the Dimensions and Metrics Reference for more information.

Filter Syntax


A single filter uses the form:

ga:name operator expression

In this syntax:

  • name — the name of the dimension or metric to filter on. For example: ga:pageviews filters on the pageviews metric.
  • operator — defines the type of filter match to use. Operators are specific to either dimensions or metrics.
  • expression — states the values to be included in or excluded from the results. Expressions use regular expression syntax.

Filter Operators


There are six filter operators for dimensions and six filter operators for metrics. The operators must be URL-encoded in order to be included in URL query strings.

Tip: Use the Data Feed Query Explorer to design filters that need URL encoding, since the Query Explorer automatically encodes URLS containing strings and spaces.

Metric Filters
Operator Description URL Encoded Form Examples
== Equals %3D%3D Return results where the time on the page is exactly ten seconds:
filters=ga:timeOnPage%3D%3D10
!= Does not equal !%3D Return results where the time on the page is not ten seconds:
filters=ga:timeOnPage!%3D10
> Greater than %3E Return results where the time on the page is strictly greater than ten seconds:
filters=ga:timeOnPage%3E10
< Less than %3C Return results where the time on the page is strictly less than ten seconds:
filters=ga:timeOnPage%3C10
>= Greater than or equal to %3E%3D Return results where the time on the page is ten seconds or more:
filters=ga:timeOnPage%3E%3D10
<= Less than or equal to %3C%3D Return results where the time on the page is ten seconds or less:
filters=ga:timeOnPage%3C%3D10

Dimension Filters
Operator Description URL Encoded Form Example
== Exact match %3D%3D Aggregate metrics where the city is Irvine:
filters=ga:city%3D%3DIrvine
!= Does not match !%3D Aggregate metrics where the city is not Irvine:
filters=ga:city!%3DIrvine
=@ Contains substring %3D@ Aggregate metrics where the city contains York:
filters=ga:city%3D@York
!@ Does not contain substring !@ Aggregate metrics where the city does not contain York:
filters=ga:city!@York
=~ Contains a match for the regular expression %3D~ Aggregate metrics where the city starts with New:
filters=ga:city%3D~%5ENew.*
(%5E is the URL encoded from of the ^ character that anchors a pattern to the beginning of the string.)
!~ Does not match regular expression !~ Aggregate metrics where the city does not start with New:
filters=ga:city!~%5ENew.*

Filter Expressions

There are a couple of important rules for filter expressions:

  • URL-reserved characters — Characters such as & must be url-encoded in the usual way.
  • Reserved characters — The semicolon and comma must be backslash escaped when they appear in an expression:
    • semicolon \;
    • comma \,
  • Regular Expressions — You can also use regular expressions in filter expressions using the =~ and !~ operators. Their syntax is similar to Perl regular expressions and have these additional rules:
    • Maximum length of 128 characters — Regular expressions longer than 128 characters result in a 400 Bad Request status code returned from the server.
    • Case sensitivity — Regular expression matching is case-insensitive.

Combining Filters

Filters can be combined using OR and AND boolean logic. This allows you to effectively extend the 128 character limit of a filter expression.

OR

The OR operator is defined using a comma (,). It takes precedence over the AND operator and may NOT be used to combine dimensions and metrics in the same expression.

Examples: (each must be URL encoded)

Country is either (United States OR Canada):
ga:country==United%20States,ga:country==Canada

Firefox users on (Windows OR Macintosh) operating systems:
ga:browser==Firefox;ga:operatingSystem==Windows,ga:operatingSystem==Macintosh

AND

The AND operator is defined using a semi-colon (;). It is preceded by the OR operator and CAN be used to combine dimensions and metrics in the same expression.

Examples: (each must be URL encoded)

Country is United States AND the browser is Firefox:
ga:country==United%20States;ga:browser==Firefox

Country is United States AND language does not start with 'en':
ga:country==United%20States;ga:language!~^en.*

Operating system is (Windows OR Macintosh) AND browser is (Firefox OR Chrome):
ga:operatingSystem==Windows,ga:operatingSystem==Macintosh;ga:browser==Firefox,ga:browser==Chrome

Country is United States AND sessions are greater than 5:
ga:country==United%20States;ga:sessions>5



segment

segment=gaid::-10
segment=sessions::condition::ga:medium%3D%3Dreferral
segment=users::condition::ga:browser%3D%3DChrome
Optional.

For complete details on how to request a segment in the Core Reporting API see the Segments Dev Guide.

For a conceptual overview of segments, see the Segments Feature Reference and Segments in the Help Center.

Dimensions and Metrics allowed in segments.
Not all dimensions and metrics can be used in segments. To review which dimensions and metrics are allowed in segments visit the Dimensions and Metrics Explorer.


samplingLevel

samplingLevel=DEFAULT
Optional.
Use this parameter to set the sampling level (i.e. the number of sessions used to calculate the result) for a reporting query. The allowed values are consistent with the web interface and include:
  • DEFAULT — Returns response with a sample size that balances speed and accuracy.
  • FASTER — Returns a fast response with a smaller sample size.
  • HIGHER_PRECISION — Returns a more accurate response using a large sample size, but this may result in the response being slower.
If not supplied, the DEFAULT sampling level will be used.
See the Sampling section for details on how to calculate the percentage of sessions that were used for a query.

include-empty-rows

include-empty-rows=true
Optional.
Defaults to true; if set to false, rows where all metric values are zero will be omitted from the response. For example if you include more than one metric in a query, the rows are only removed if all metric values are zero. This can be useful when making a request where it is expected that the number of valid rows is much smaller then the number of expected dimension values.

start-index

start-index=10
Optional.
If not supplied, the starting index is 1. (Result indexes are 1-based. That is, the first row is row 1, not row 0.) Use this parameter as a pagination mechanism along with the max-results parameter for situations when totalResults exceeds 10,000 and you want to retrieve rows indexed at 10,001 and beyond.

max-results

max-results=100
Optional.
Maximum number of rows to include in this response. You can use this in combination with start-index to retrieve a subset of elements, or use it alone to restrict the number of returned elements, starting with the first. If max-results is not supplied, the query returns the default maximum of 1000 rows.
The Analytics Core Reporting API returns a maximum of 10,000 rows per request, no matter how many you ask for. It can also return fewer rows than requested, if there aren't as many dimension segments as you expect. For instance, there are fewer than 300 possible values for ga:country, so when segmenting only by country, you can't get more than 300 rows, even if you set max-results to a higher value.

output

output=dataTable
Optional.
Use this parameter to set the output type of the Analytics data returned in the response. The allowed values are:
  • json — Outputs the default rows property in the response, containing a JSON object.
  • dataTable — Outputs a dataTable property in the response, containing a Data Table object. This Data Table object can be used directly with Google Charts visualizations.
If not supplied, the default JSON response will be used.

fields

fields=rows,columnHeaders(name,dataType)
Optional.

Specifies which fields to return in a partial response. If you only use a subset of the fields in the API response, you can use the fields parameter to specify which fields to include.

The format of the fields request parameter value is loosely based on XPath syntax. The supported syntax is summarized below.

  • Use a comma-separated list to select multiple fields.
  • Use a/b to select a field b that is nested within field a; use a/b/c to select a field c nested within b.
  • Use a sub-selector to request a set of specific sub-fields of arrays or objects by placing expressions in parentheses "( )".
    For example: fields=columnHeaders(name,dataType) returns only the name and dataType fields in the columnHeaders array. You can also specify a single sub-field, where fields=columnHeader(name) is equivalent to fields=columnHeader/name.

prettyPrint

prettyPrint=false
Optional.

Returns the response in a human-readable format if true. Default value: false.


quotaUser

quotaUser=4kh4r2h4
Optional.

Lets you enforce per-user quotas from a server-side application even in cases when the user's IP address is unknown. This can occur, for example, with applications that run cron jobs on App Engine on a user's behalf. You can choose any arbitrary string that uniquely identifies a user, but it is limited to 40 characters.

This overrides userIp if both are provided.


Response

If successful, this request returns a response body with the JSON structure defined below. If the output parameter is set to dataTable then the request returns a response body with the JSON (Data Table) structure defined below.

Note: the term "results" refers to the entire set of rows that match the query, while "response" refers to the set of rows returned on the current page of results. They can be different if the total number results is greater than the page size for the current response, as explained in itemsPerPage.

JSON
{
  "kind": "analytics#gaData",
  "id": string,
  "selfLink": string,
  "containsSampledData": boolean,
  "query": {
    "start-date": string,
    "end-date": string,
    "ids": string,
    "dimensions": [
      string
    ],
    "metrics": [
      string
    ],
    "include-empty-rows": boolean
    "samplingLevel": string,
    "sort": [
      string
    ],
    "filters": string,
    "segment": string,
    "start-index": integer,
    "max-results": integer
  },
  "itemsPerPage": integer,
  "totalResults": integer,
  "previousLink": string,
  "nextLink": string,
  "profileInfo": {
    "profileId": string,
    "accountId": string,
    "webPropertyId": string,
    "internalWebPropertyId": string,
    "profileName": string,
    "tableId": string
  },
  "columnHeaders": [
    {
      "name": string,
      "columnType": string,
      "dataType": string
    }
  ],
  "rows": [
    [
      string
    ]
  ],
  "sampleSize": string,
  "sampleSpace": string,
  "totalsForAllResults": [
    {
      metricName: string,
      ...
    }
  ]
}

Response Fields

The properties of the response body structure are defined as follows:

Property Name Value Description
kind string Resource type. Value is "analytics#gaData".
id string An ID for this data response.
query object This object contains all the values passed as parameters to the query. The meaning of each field is explained in the description of its corresponding query parameter.
query.start-date string Start date.
query.end-date string End date.
query.ids string Unique table ID.
query.dimensions[] list List of analytics dimensions.
query.metrics[] list List of analytics metrics.
query.samplingLevel string Requested sampling level.
query.include-empty-rows boolean Defaults to true; if set to false, rows where all metric values are zero will be omitted from the response.
query.sort[] list List of metrics or dimensions on which the data is sorted.
query.filters string Comma-separated list of metric or dimension filters.
query.segment string Analytics segment.
query.start-index integer Start index.
query.max-results integer Maximum results per page.
startIndex integer The starting index of rows specified by the start-index query parameter. Default value is 1.
itemsPerPage integer The maximum number of rows the response can contain, regardless of the actual number of rows returned. If the max-results query parameter is specified, the value of itemsPerPage is the smaller of max-results or 10,000. The default value of itemsPerPage is 1000.
totalResults integer The total number of rows in the query result, regardless of the number of rows returned in the response. For queries that result in a large number of rows, totalResults can be greater than itemsPerPage. See Paging for more explanation of totalResults and itemsPerPage for large queries.
startDate string Start date for the data query, as specified by the start-date parameter.
endDate string End date for the data query, as specified by the end-date parameter.
profileInfo object Information about the view (profile) for which the data was requested. View (Profile) data is available through the Google Analytics Management API.
profileInfo.profileId string View (Profile) ID, such as 1174.
profileInfo.accountId string Account ID to which this view (profile) belongs, such as 30481.
profileInfo.webPropertyId string Web Property ID to which this view (profile) belongs, such as UA-30481-1.
profileInfo.internalWebPropertyId string Internal ID for the web property to which this view (profile) belongs, such as UA-30481-1.
profileInfo.profileName string Name of the view (profile).
profileInfo.tableId string Table ID for view (profile), consisting of "ga:" followed by the view (profile) ID.
containsSampledData boolean True if the response contains sampled data.
sampleSize string The number of samples used to calculate the sampled data.
sampleSpace string The total sampling space size. This indicates the total available sample space size from which the samples were selected.
columnHeaders[] list Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as those specified in the request through the metrics and dimensions parameters. The number of headers is the number of dimensions + the number of metrics.
columnHeaders[].name string Name of the dimension or metric.
columnHeaders[].columnType string Column type. Either "DIMENSION" or "METRIC".
columnHeaders[].dataType string Data type. Dimension column headers have only STRING as data type. Metric column headers have data types for metric values such as INTEGER, PERCENT, TIME, CURRENCY, FLOAT, etc. See the metadata API response for all the possible data types.
totalsForAllResults object Total values for the requested metrics as key-value pairs of metric names and values. The order of the metric totals is same as the metric order specified in the request.
rows[] list Analytics data rows, where each row contains a list of dimension values followed by the metric values. The order of dimensions and metrics is same as specified in the request. Each row has a list of N fields, where N = the number of dimensions + the number of metrics.
JSON (Data Table)
{
  "kind": "analytics#gaData",
  "id": string,
  "selfLink": string,
  "containsSampledData": boolean,
  "query": {
    "start-date": string,
    "end-date": string,
    "ids": string,
    "dimensions": [
      string
    ],
    "metrics": [
      string
    ],
    "samplingLevel": string,
    "include-empty-rows": boolean,
    "sort": [
      string
    ],
    "filters": string,
    "segment": string,
    "start-index": integer,
    "max-results": integer
  },
  "itemsPerPage": integer,
  "totalResults": integer,
  "previousLink": string,
  "nextLink": string,
  "profileInfo": {
    "profileId": string,
    "accountId": string,
    "webPropertyId": string,
    "internalWebPropertyId": string,
    "profileName": string,
    "tableId": string
  },
  "columnHeaders": [
    {
      "name": string,
      "columnType": string,
      "dataType": string
    }
  ],
  "dataTable": {
    "cols": [
      {
        "id": string,
        "label": string,
        "type": string
      }
    ],
    "rows": [
      {
        "c": [
          {    
            "v": string
          }
        ]
      }   
    ]
  },
  "sampleSize": string,
  "sampleSpace": string,
  "totalsForAllResults": [
    {
      metricName: string,
      ...
    }
  ]
}

Response Fields

The properties of the response body structure are defined as follows:

Property Name Value Description
kind string Resource type. Value is "analytics#gaData".
id string An ID for this data response.
query object This object contains all the values passed as parameters to the query. The meaning of each field is explained in the description of its corresponding query parameter.
query.start-date string Start date.
query.end-date string End date.
query.ids string Unique table ID.
query.dimensions[] list List of analytics dimensions.
query.metrics[] list List of analytics metrics.
query.samplingLevel string Requested sampling level.
query.include-empty-rows boolean Defaults to true; if set to false, rows where all metric values are zero will be omitted from the response.
query.sort[] list List of metrics or dimensions on which the data is sorted.
query.filters string Comma-separated list of metric or dimension filters.
query.segment string Analytics segment.
query.start-index integer Start index.
query.max-results integer Maximum results per page.
startIndex integer The starting index of rows specified by the start-index query parameter. Default value is 1.
itemsPerPage integer The maximum number of rows the response can contain, regardless of the actual number of rows returned. If the max-results query parameter is specified, the value of itemsPerPage is the smaller of max-results or 10,000. The default value of itemsPerPage is 1000.
totalResults integer The total number of rows in the query result, regardless of the number of rows returned in the response. For queries that result in a large number of rows, totalResults can be greater than itemsPerPage. See Paging for more explanation of totalResults and itemsPerPage for large queries.
startDate string Start date for the data query, as specified by the start-date parameter.
endDate string End date for the data query, as specified by the end-date parameter.
profileInfo object Information about the view (profile) for which the data was requested. View (Profile) data is available through the Google Analytics Management API.
profileInfo.profileId string View (Profile) ID, such as 1174.
profileInfo.accountId string Account ID to which this view (profile) belongs, such as 30481.
profileInfo.webPropertyId string Web Property ID to which this view (profile) belongs, such as UA-30481-1.
profileInfo.internalWebPropertyId string Internal ID for the web property to which this view (profile) belongs, such as UA-30481-1.
profileInfo.profileName string Name of the view (profile).
profileInfo.tableId string Table ID for view (profile), consisting of "ga:" followed by the view (profile) ID.
containsSampledData boolean True if the response contains sampled data.
sampleSize string The number of samples used to calculate the sampled data.
sampleSpace string The total sampling space size. This indicates the total available sample space size from which the samples were selected.
columnHeaders[] list Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as those specified in the request through the metrics and dimensions parameters. The number of headers is the number of dimensions + the number of metrics.
columnHeaders[].name string Name of the dimension or metric.
columnHeaders[].columnType string Column type. Either "DIMENSION" or "METRIC".
columnHeaders[].dataType string Data type. Dimension column headers have only STRING as data type. Metric column headers have data types for metric values such as INTEGER, PERCENT, TIME, CURRENCY, FLOAT, etc. See the metadata API response for all the possible data types.
totalsForAllResults object Total values for the requested metrics as key-value pairs of metric names and values. The order of the metric totals is same as the metric order specified in the request.
dataTable object A Data Table object that can be used with Google Charts.
dataTable.cols[] list A list of column descriptors for dimensions followed by metrics. The order of dimensions and metrics is the same as those specified in the request through the metrics and dimensions parameters. The number of columns is the number of dimensions + the number of metrics.
dataTable.cols[].id string An ID, which can be used to refer to a specific column (as an alternative to using column indexes). The dimension or metric Id is used to set this value.
dataTable.cols[].label string A label for the column (which might be displayed by a visualization). The dimension or metric Id is used to set this value.
dataTable.cols[].type string The data type for this column.
dataTable.rows[] list Analytics data rows in Data Table format, where each row is an object containing a list of cell values for dimensions followed by metrics. The order of dimensions and metrics is same as specified in the request. Each cell has a list of N fields, where N = the number of dimensions + the number of metrics.

Error Codes

The Core Reporting API returns a 200 HTTP status code if a request is successful. If there an error occurs during processing of a query, the API returns an error code and description. Each application that uses the analytics API needs to implement proper error handling logic. For details on the error codes and how to handle them, read the Error Responses reference guide.

Try It!

You can try out queries to the Core Reporting API.

  • To see the valid combinations of metrics and dimensions in a query, enter sample values for the parameters in the Query Explorer. The results of the sample query are shown as a table with values for all the specified metrics and dimensions.

  • To make a request on live data and see the response in JSON format, try the analytics.data.ga.get method in the Google Data APIs Explorer.

Sampling

Google Analytics calculates certain combinations of dimensions and metrics on the fly. To return the data in a reasonable time, Google Analytics may only process a sample of the data.

You can specify the sampling level to use for a request by setting the samplingLevel parameter.

If a Core Reporting API response contains sampled data, then the containsSampledData response field will be true. In addition, 2 properties will provide information about the sampling level for the query: sampleSize and sampleSpace. With these 2 values you can calculate the percentage of sessions that were used for the query. For example, if sampleSize is 201,000 and sampleSpace is 220,000 then the report is based on (201,000 / 220,000) * 100 = 91.36% of sessions.

See Sampling for a general description of sampling and how it is used in Google Analytics.


Handling Large Data Results

If you expect your query to return a large result set, use the guidelines below to help you optimize your API query, avoid errors, and minimize quota overruns. Note that we set a performance baseline by allowing a maximum of 7 dimensions and 10 metrics in any one API request. Although some queries that specify large numbers of metrics and dimensions may take longer to process than others, limiting the number of requested metrics might not be enough to improve query performance. Instead, you can use the following techniques for the best performance results.

Reducing Dimensions per Query

The API allows specifying up to 7 dimensions in any one request. Many times, Google Analytics must calculate the results of these complex queries on the fly. This can be especially time consuming if the number of resulting rows is high. For example, querying for keywords, by city by hour may match millions of rows of data. You can improve performance by reducing the number of rows Google Analytics needs to process by limiting the number of dimensions in your query.

Splitting the Query by Date Range

Instead of paging through the date-keyed results of one long date range, consider forming separate queries for one week — or even one day — at a time. Of course, for a large data set, even a request for a single day's data might return more than max-results, in which case paging cannot be avoided. But in any case, if the number of matching rows for your query is higher than max-results, breaking apart the date range may decrease the total time to retrieve the results. This approach can improve performance in both single-threaded and parallel queries.

Paging

Paging through results can be a useful way to break large results sets into manageable chunks. The totalResults field tells how many matching rows exist, and itemsPerPage gives the maximum number of rows that can be returned in the result. If there is a high ratio of totalResults to itemsPerPage, then the individual queries might be taking longer than necessary. If you need only a limited number of rows, such as for display purposes, you may find it convenient to set an explicit limit on response size through the max-results parameter. However, if your application needs to process a large set of results in its entirety, then requesting the maximum allowed rows may be more efficient.

Using gzip

An easy and convenient way to reduce the bandwidth needed for each request is to enable gzip compression. Although this requires additional CPU time to uncompress the results, the tradeoff with network costs usually makes it very worthwhile. In order to receive a gzip-encoded response you must do two things: Set an Accept-Encoding header, and modify your user agent to contain the string gzip. Here is an example of properly formed HTTP headers for enabling gzip compression:

Accept-Encoding: gzip
User-Agent: my program (gzip)