# Query Metric Aggregates

Query and aggregate event data associated with a metric, including native Klaviyo metrics, integration-specific metrics, and custom events. Queries must be passed in the JSON body of your `POST` request.

Results can be filtered and grouped by time, event, or profile dimensions.

To learn more about how to use this endpoint, check out our new [Using the Query Metric Aggregates Endpoint guide](https://developers.klaviyo.com/en/docs/using-the-query-metric-aggregates-endpoint).

**Request body parameters** (nested under `attributes`):

* `return_fields`: request specific fields using [sparse fieldsets](https://developers.klaviyo.com/en/reference/api_overview#sparse-fieldsets)
* `sort`: sort results by a specified field, such as `"-timestamp"`
* `page_cursor`: results can be paginated with [cursor-based pagination](https://developers.klaviyo.com/en/reference/api_overview#pagination)
* `page_size`: limit the number of returned results per page
* `by`: optional attributes used to group by the aggregation function
    * When using `by` attributes, an empty `dimensions` response is expected when the counts for the events do not have the associated dimension requested by the set `by` attribute. For example, a query including `"by": ["$flow"]` will return an empty dimensions response for counts of metrics not associated with a `$flow`
* `measurement`: the measurement key supports the following values:
    * `"sum_value"`: perform a summation of the `_Event Value_`, optionally partitioned over any dimension provided in the `by` field
    * `"count"`: counts the number of events associated to a metric, optionally partitioned over any dimension provided in the `by` field
    * `"unique"` counts the number of unique customers associated to a metric, optionally partitioned over any dimension provided in the `by` field
* `interval`: aggregation interval, such as `"hour"`,`"day"`,`"week"`, and `"month"`
* `metric_id`: the metric ID used in the aggregation
* `filter`: list of filters for specific fields, must include time range using ISO 8601 format (`"YYYY-MM-DDTHH:MM:SS.mmmmmm"`)
    * The time range can be filtered by providing a `greater-or-equal` filter on the datetime field, such as `"greater-or-equal(datetime,2021-07-01T00:00:00)"` and a `less-than` filter on the same datetime field, such as `"less-than(datetime,2022-07-01T00:00:00)"`
    * The time range may span a maximum of one year. Time range dates may be set to a maximum of 5 years prior to the current date
    * Filter the list of supported aggregate dimensions using the common filter syntax, such as `"equals(URL,\"https://www.klaviyo.com/\")"`
* `timezone`: the timezone used when processing the query. Case sensitive. This field is validated against a list of common timezones from the [IANA Time Zone Database](https://www.iana.org/time-zones)
    * While the payload accepts a timezone, the response datetimes returned will be in UTC.

For a comprehensive list of native Klaviyo metrics and their associated attributes for grouping and filtering, please refer to the [metrics attributes guide](https://developers.klaviyo.com/en/docs/supported_metrics_and_attributes).<br><br>*Rate limits*:<br>Burst: `3/s`<br>Steady: `60/m`

**Scopes:**
`metrics:read`

# OpenAPI definition

```json
{
  "openapi": "3.0.2",
  "info": {
    "title": "Metrics API",
    "version": "2023-09-15",
    "description": "The Klaviyo REST API. Please visit https://developers.klaviyo.com for more details.",
    "contact": {
      "name": "Klaviyo Developer Experience Team",
      "email": "developers@klaviyo.com",
      "url": "https://developers.klaviyo.com"
    },
    "termsOfService": "https://www.klaviyo.com/legal/api-terms",
    "license": {
      "name": "License",
      "url": "https://www.klaviyo.com/legal"
    }
  },
  "servers": [
    {
      "url": "https://a.klaviyo.com",
      "description": "Production"
    }
  ],
  "paths": {
    "/api/metric-aggregates/": {
      "post": {
        "operationId": "query_metric_aggregates",
        "summary": "Query Metric Aggregates",
        "description": "Query and aggregate event data associated with a metric, including native Klaviyo metrics, integration-specific metrics, and custom events. Queries must be passed in the JSON body of your `POST` request.\n\nResults can be filtered and grouped by time, event, or profile dimensions.\n\nTo learn more about how to use this endpoint, check out our new [Using the Query Metric Aggregates Endpoint guide](https://developers.klaviyo.com/en/docs/using-the-query-metric-aggregates-endpoint).\n\n**Request body parameters** (nested under `attributes`):\n\n* `return_fields`: request specific fields using [sparse fieldsets](https://developers.klaviyo.com/en/reference/api_overview#sparse-fieldsets)\n* `sort`: sort results by a specified field, such as `\"-timestamp\"`\n* `page_cursor`: results can be paginated with [cursor-based pagination](https://developers.klaviyo.com/en/reference/api_overview#pagination)\n* `page_size`: limit the number of returned results per page\n* `by`: optional attributes used to group by the aggregation function\n    * When using `by` attributes, an empty `dimensions` response is expected when the counts for the events do not have the associated dimension requested by the set `by` attribute. For example, a query including `\"by\": [\"$flow\"]` will return an empty dimensions response for counts of metrics not associated with a `$flow`\n* `measurement`: the measurement key supports the following values:\n    * `\"sum_value\"`: perform a summation of the `_Event Value_`, optionally partitioned over any dimension provided in the `by` field\n    * `\"count\"`: counts the number of events associated to a metric, optionally partitioned over any dimension provided in the `by` field\n    * `\"unique\"` counts the number of unique customers associated to a metric, optionally partitioned over any dimension provided in the `by` field\n* `interval`: aggregation interval, such as `\"hour\"`,`\"day\"`,`\"week\"`, and `\"month\"`\n* `metric_id`: the metric ID used in the aggregation\n* `filter`: list of filters for specific fields, must include time range using ISO 8601 format (`\"YYYY-MM-DDTHH:MM:SS.mmmmmm\"`)\n    * The time range can be filtered by providing a `greater-or-equal` filter on the datetime field, such as `\"greater-or-equal(datetime,2021-07-01T00:00:00)\"` and a `less-than` filter on the same datetime field, such as `\"less-than(datetime,2022-07-01T00:00:00)\"`\n    * The time range may span a maximum of one year. Time range dates may be set to a maximum of 5 years prior to the current date\n    * Filter the list of supported aggregate dimensions using the common filter syntax, such as `\"equals(URL,\\\"https://www.klaviyo.com/\\\")\"`\n* `timezone`: the timezone used when processing the query. Case sensitive. This field is validated against a list of common timezones from the [IANA Time Zone Database](https://www.iana.org/time-zones)\n    * While the payload accepts a timezone, the response datetimes returned will be in UTC.\n\nFor a comprehensive list of native Klaviyo metrics and their associated attributes for grouping and filtering, please refer to the [metrics attributes guide](https://developers.klaviyo.com/en/docs/supported_metrics_and_attributes).<br><br>*Rate limits*:<br>Burst: `3/s`<br>Steady: `60/m`\n\n**Scopes:**\n`metrics:read`",
        "parameters": [
          {
            "name": "revision",
            "in": "header",
            "description": "API endpoint revision (format: YYYY-MM-DD[.suffix])",
            "required": true,
            "schema": {
              "type": "string",
              "default": "2023-09-15"
            }
          }
        ],
        "requestBody": {
          "description": "Retrieve Metric Aggregations",
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MetricAggregateQuery"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PostMetricAggregateResponse"
                }
              }
            }
          },
          "4XX": {
            "description": "",
            "$ref": "#/components/responses/ClientError"
          },
          "5XX": {
            "description": "",
            "$ref": "#/components/responses/ServerError"
          }
        },
        "tags": [
          "Metrics"
        ],
        "x-klaviyo-pre-release": "None",
        "x-klaviyo-ratelimit": {
          "burst": "3/s",
          "steady": "60/m"
        },
        "x-klaviyo-scopes": [
          "metrics:read"
        ]
      }
    }
  },
  "components": {
    "schemas": {
      "MetricAggregateQueryResourceObject": {
        "type": "object",
        "properties": {
          "type": {
            "$ref": "#/components/schemas/MetricAggregateEnum"
          },
          "attributes": {
            "type": "object",
            "properties": {
              "metric_id": {
                "description": "The metric ID used in the aggregation.",
                "type": "string",
                "example": "0rG4eQ",
                "default": "0rG4eQ"
              },
              "page_cursor": {
                "description": "Optional pagination cursor to iterate over large result sets",
                "type": "string"
              },
              "measurements": {
                "description": "Measurement key, e.g. `unique`, `sum_value`, `count`",
                "type": "array",
                "items": {
                  "type": "string",
                  "enum": [
                    "count",
                    "sum_value",
                    "unique"
                  ],
                  "description": "Supported measurements for aggregation"
                },
                "example": "count",
                "default": "count"
              },
              "interval": {
                "description": "Aggregation interval, e.g. \"hour\", \"day\", \"week\", \"month\"",
                "type": "string",
                "example": "day",
                "default": "day",
                "enum": [
                  "day",
                  "hour",
                  "month",
                  "week"
                ]
              },
              "page_size": {
                "description": "Alter the maximum number of returned rows in a single page of aggregation results",
                "type": "integer",
                "example": 500,
                "default": 500
              },
              "by": {
                "description": "Optional attribute(s) used for partitioning by the aggregation function",
                "type": "array",
                "items": {
                  "type": "string",
                  "enum": [
                    "$attributed_channel",
                    "$attributed_flow",
                    "$attributed_message",
                    "$attributed_variation",
                    "$campaign_channel",
                    "$flow",
                    "$flow_channel",
                    "$message",
                    "$message_send_cohort",
                    "$variation",
                    "$variation_send_cohort",
                    "Bounce Type",
                    "Campaign Name",
                    "Client Canonical",
                    "Client Name",
                    "Client Type",
                    "Email Domain",
                    "Failure Source",
                    "Failure Type",
                    "From Number",
                    "From Phone Region",
                    "List",
                    "Message Name",
                    "Message Type",
                    "Method",
                    "Subject",
                    "To Number",
                    "To Phone Region",
                    "URL",
                    "form_id"
                  ],
                  "description": "Supported dimensions for grouping and filtering"
                },
                "example": "$message",
                "default": "$message"
              },
              "return_fields": {
                "description": "Provide fields to limit the returned data",
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              "filter": {
                "description": "List of filters, must include time range using ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm).\n            These filters follow a similar format to those in `GET` requests, the primary difference is that this endpoint asks for a list.\n            The time range can be filtered by providing a `greater-or-equal` and a `less-than` filter on the `datetime` field.",
                "type": "array",
                "items": {
                  "type": "string"
                },
                "example": [
                  "greater-or-equal(datetime,2022-12-01T00:00:00)",
                  "less-than(datetime,2022-12-08T00:00:00"
                ],
                "default": [
                  "greater-or-equal(datetime,2022-12-01T00:00:00)",
                  "less-than(datetime,2022-12-08T00:00:00"
                ]
              },
              "timezone": {
                "description": "The timezone used for processing the query, e.g. `'America/New_York'`.\n            This field is validated against a list of common timezones from the [IANA Time Zone Database](https://www.iana.org/time-zones).\n            While most are supported, a few notable exceptions are `Factory`, `Europe/Kyiv` and `Pacific/Kanton`. This field is case-sensitive.",
                "type": "string",
                "example": "America/New_York",
                "default": "UTC"
              },
              "sort": {
                "description": "Provide a sort key (e.g. -$message)",
                "type": "string",
                "enum": [
                  "$attributed_channel",
                  "-$attributed_channel",
                  "$attributed_flow",
                  "-$attributed_flow",
                  "$attributed_message",
                  "-$attributed_message",
                  "$attributed_variation",
                  "-$attributed_variation",
                  "$campaign_channel",
                  "-$campaign_channel",
                  "$flow",
                  "-$flow",
                  "$flow_channel",
                  "-$flow_channel",
                  "$message",
                  "-$message",
                  "$message_send_cohort",
                  "-$message_send_cohort",
                  "$variation",
                  "-$variation",
                  "$variation_send_cohort",
                  "-$variation_send_cohort",
                  "Bounce Type",
                  "-Bounce Type",
                  "Campaign Name",
                  "-Campaign Name",
                  "Client Canonical",
                  "-Client Canonical",
                  "Client Name",
                  "-Client Name",
                  "Client Type",
                  "-Client Type",
                  "Email Domain",
                  "-Email Domain",
                  "Failure Source",
                  "-Failure Source",
                  "Failure Type",
                  "-Failure Type",
                  "From Number",
                  "-From Number",
                  "From Phone Region",
                  "-From Phone Region",
                  "List",
                  "-List",
                  "Message Name",
                  "-Message Name",
                  "Message Type",
                  "-Message Type",
                  "Method",
                  "-Method",
                  "Subject",
                  "-Subject",
                  "To Number",
                  "-To Number",
                  "To Phone Region",
                  "-To Phone Region",
                  "URL",
                  "-URL",
                  "count",
                  "-count",
                  "form_id",
                  "-form_id",
                  "sum_value",
                  "-sum_value",
                  "unique",
                  "-unique"
                ]
              }
            },
            "required": [
              "metric_id",
              "measurements",
              "filter"
            ]
          }
        },
        "required": [
          "type",
          "attributes"
        ]
      },
      "MetricAggregateQuery": {
        "type": "object",
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MetricAggregateQueryResourceObject"
          }
        },
        "required": [
          "data"
        ]
      },
      "MetricAggregateRowDTO": {
        "type": "object",
        "properties": {
          "dimensions": {
            "description": "List of dimensions associated with this set of measurements",
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "measurements": {
            "description": "Dictionary of measurement_key, values",
            "type": "object"
          }
        },
        "required": [
          "dimensions",
          "measurements"
        ]
      },
      "PostMetricAggregateResponse": {
        "type": "object",
        "properties": {
          "data": {
            "type": "object",
            "properties": {
              "type": {
                "$ref": "#/components/schemas/MetricAggregateEnum"
              },
              "id": {
                "description": "Ephemeral ID associated with the aggregation query",
                "type": "string"
              },
              "attributes": {
                "type": "object",
                "properties": {
                  "dates": {
                    "description": "The dates of the query range",
                    "type": "array",
                    "items": {
                      "type": "string",
                      "format": "date-time"
                    }
                  },
                  "data": {
                    "description": "Aggregation result data",
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/MetricAggregateRowDTO"
                    }
                  }
                },
                "required": [
                  "dates",
                  "data"
                ]
              },
              "links": {
                "$ref": "#/components/schemas/ObjectLinks"
              }
            },
            "required": [
              "type",
              "id",
              "attributes",
              "links"
            ]
          }
        },
        "required": [
          "data"
        ]
      },
      "ObjectLinks": {
        "type": "object",
        "properties": {
          "self": {
            "type": "string",
            "format": "uri"
          }
        },
        "required": [
          "self"
        ]
      },
      "MetricAggregateEnum": {
        "type": "string",
        "enum": [
          "metric-aggregate"
        ]
      }
    },
    "responses": {
      "ClientError": {
        "description": "Client Error",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "errors": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "id",
                      "code",
                      "title",
                      "detail"
                    ],
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "code": {
                        "type": "string"
                      },
                      "title": {
                        "type": "string"
                      },
                      "detail": {
                        "type": "string"
                      },
                      "source": {
                        "type": "object",
                        "properties": {
                          "pointer": {
                            "type": "string"
                          },
                          "parameter": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                }
              },
              "required": [
                "errors"
              ]
            }
          }
        }
      },
      "ServerError": {
        "description": "Server Error",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "properties": {
                "errors": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": [
                      "id",
                      "code",
                      "title",
                      "detail"
                    ],
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "code": {
                        "type": "string"
                      },
                      "title": {
                        "type": "string"
                      },
                      "detail": {
                        "type": "string"
                      },
                      "source": {
                        "type": "object",
                        "properties": {
                          "pointer": {
                            "type": "string"
                          },
                          "parameter": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                }
              },
              "required": [
                "errors"
              ]
            }
          }
        }
      }
    },
    "securitySchemes": {
      "Klaviyo-API-Key": {
        "type": "apiKey",
        "in": "header",
        "name": "Authorization",
        "description": "Private key authentication for /api/ endpoints is performed by setting the `Authorization` header to `Klaviyo-API-Key your-private-api-key`<br>For more information please visit https://developers.klaviyo.com/en/v2023-09-15/reference/api-overview#authentication",
        "x-default": "Klaviyo-API-Key your-private-api-key"
      }
    }
  },
  "tags": [
    {
      "name": "Metrics"
    }
  ],
  "security": [
    {
      "Klaviyo-API-Key": []
    }
  ],
  "x-readme": {
    "explorer-enabled": false,
    "proxy-enabled": true,
    "samples-enabled": true
  },
  "_id": {
    "buffer": {
      "0": 101,
      "1": 4,
      "2": 167,
      "3": 253,
      "4": 13,
      "5": 221,
      "6": 170,
      "7": 0,
      "8": 80,
      "9": 131,
      "10": 52,
      "11": 211
    }
  }
}
```