> This page is for version Preview (default).
> For other versions, use one of these documentation indexes:
> - Preview (default): https://docs.preview.paid.ai/preview/llms.txt
> - Current: https://docs.preview.paid.ai/current/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.preview.paid.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.preview.paid.ai/_mcp/server.

# Query metrics

POST https://api.paid.ai/v1/metrics/query
Content-Type: application/json

Aggregates usage events (the `events` view) or credit movements (the `credits` view) over a window: counts, and on `credits` sums of `amount`, split by any field of the view and optionally by hour, day, week or month. Returns one result with every row and no cursor; a query that could return more than 50,000 rows (groups × periods) is refused before it runs with `invalid_request`, `param` naming what to narrow. Reads the narrowest pre-summed table that holds every grouped and filtered field (`eventName` aside), and raw events otherwise, with the window capped at 31 days, or 90 with a customer filter on a read by name; a `credits` query reads the credit ledger's copy, about a minute behind it, with no window cap; a `metadata` query folds the raw events sharing a value of the payload key `key` names into entities, with the window capped at 31 days, or 90 with a customer filter. `readFrom` says which. A read, sent as a POST because the query is a structured body: it creates nothing and is safe to retry.

Reference: https://docs.preview.paid.ai/api-reference/metering/metrics/query

## Authentication

- `Authorization` header (bearer token, required) — API Key authentication using Bearer token

## Request

### Headers

- `Paid-Beta` (enum, required) — This endpoint is in the `metrics=v1` beta. Send this header to use it.
  - Allowed values: `metrics=v1`

### Body (application/json)

This endpoint expects a QueryMetricsRequest.

- `view` (string, required) — The view to read, by the `key` `GET /v1/metrics/views` lists: `events` (usage events), `credits` (credit spends and grants) or `metadata` (entities: one customer's events sharing a value of the payload key `key` names). More views may be added.
- `aggregations` (list of MetricsAggregationInput, optional) — The figures each row carries, 1 to 10, each pair once. Defaults to `[{ "aggregation": "count" }]`. On `credits`, a `sum` needs one credit currency: filter `creditCurrency` with `eq`, else `invalid_request` naming `aggregations`; or group by `creditCurrency` alone, with `groupLimit` at least the account's number of credit currencies, else `invalid_request` naming `groupLimit`.
- `endsAt` (datetime, optional) — Exclusive end of the window, on a whole UTC hour and after `startsAt`. Leave it out to end at the first whole UTC hour after `asOf`, so the hour in progress is included.
- `filters` (list of MetricsFilter, optional) — Conditions every counted event or credit movement meets, up to 20, all of which must hold. Any field of the view can be filtered on. On `credits`, no `type` filter reads spends and grants both.
- `granularity` (enum, optional) — The length of each period. Leave it out to treat the whole window as one period. With it, the window holds at most 250 periods.
  - Allowed values: `hour`, `day`, `week`, `month`
- `groupBy` (list of string, optional) — Fields to split the rows by, up to 20, each once. Any field of the view can be grouped by. Defaults to `[]`: one row per period.
- `groupLimit` (integer, optional, default: 100) — How many groups to keep, 1 to 10,000 without `granularity` and 1 to 1,000 with it (over is `invalid_request` naming `groupLimit`), ranked by `rankBy`, else by event (or movement) count, largest first, over the whole window, ties broken by the stored value. The rest fold into one remainder row per period, with `remainder: true` and every `group` value null. Defaults to 100. With `groupBy`, (`groupLimit` + 1) × periods can be at most 50,000 rows; over it is `invalid_request` naming `groupLimit`.
- `key` (MetricsKey, optional) — The entity the `metadata` view folds events into. Required with `view: "metadata"`, and `invalid_request` naming `key` with any other view.
- `rankBy` (MetricsRankBy, optional) — Which of the request's aggregations ranks the groups, and which way. Groups are ranked by that figure over the whole window (an `avg` as the window's sum over its count), ties broken by the stored value, a null figure (an `avg`, `min` or `max` over no numbers) last either way: the first `groupLimit` are kept, and within a period rows come by that figure, then by group value, the remainder row last. Needs `groupBy`, and the pair must be one of `aggregations`; else `invalid_request` naming `rankBy`. Leave it out to rank by count, largest first.
- `startsAt` (datetime, optional) — Inclusive start of the window, on a whole UTC hour. Events count by their `timestamp`, when they happened; credit movements by when billing places them. Leave it out to start at the first hour the view holds data for the account; with `endsAt` left out too, the window is all time. The result's `window` says where it started.

## Response

### 200

200

- `object` (enum, required) — The type of object. Always `metricsResult`.
  - Allowed values: `metricsResult`
- `asOf` (datetime, required) — When the figures were computed.
- `data` (list of MetricsRow, required) — Every row of the result, by period, then by `rankBy`'s figure (then group value), else by group value in byte order. The remainder row, the one with `remainder: true`, is the last of its period. At most 50,000.
- `granularity` (enum, required) — The request's `granularity`, or null when it had none and each group has one row for the whole window.
  - Allowed values: `hour`, `day`, `week`, `month`
- `groups` (MetricsGroups, required) — How many groups the window held. Null when the request had no `groupBy`.
- `key` (MetricsResultKey, required) — On `metadata`, the request's `key` with `from` resolved. Null on every other view.
- `readFrom` (enum, required) — `rollup` when a pre-summed table answered the query; `events` when it was read from raw events, which caps the window at 31 days (90 with a customer filter on a read by name), as every `events` query with a `countDistinct`, or a `sum`, `avg`, `min`, `max` or `count` of a payload field, is. The figures are the same either way. `ledger` on every `credits` query: the credit ledger's copy, about a minute behind it. `events` on every `metadata` query. More values may be added.
  - Allowed values: `rollup`, `events`, `ledger`
- `view` (string, required) — The view the rows were read from.
- `window` (MetricsWindow, required) — The window the figures cover, as resolved from the request: what a query that left out `startsAt` or `endsAt` read.

## Errors

### 400 Bad Request Error

400

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 401 Unauthorized Error

401

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 403 Forbidden Error

403

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 409 Conflict Error

409

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 429 Too Many Requests Error

429

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 500 Internal Server Error

500

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

## Types

### MetricsAggregationInput

One figure to compute for each row.

- `aggregation` (enum, required) — How rows are combined: `count` counts them (events, credit movements, or entities on `metadata`), or with a `payload.<key>` field the rows whose value is a number; `sum`, `avg`, `min` and `max` take a numeric field (`payload.<key>` on every view, `amount` on `credits`, `credits` on `metadata`); `countDistinct` counts the distinct values of `field`, any field `groupBy` takes. A payload value is a number when it is a JSON number or a string holding one (`"42"`, `"1.5"`), of magnitude under 10^40; any other value is skipped, never an error. More values may be added.
  - Allowed values: `count`, `sum`, `countDistinct`, `avg`, `min`, `max`
- `field` (string, optional) — The field to aggregate. Leave it out for `count` to count rows; every other aggregation needs one. The pair must be one the view lists; `sum`, `avg`, `min`, `max` and `count` take any `payload.<key>`, and `countDistinct` any field `groupBy` takes, a payload path the views list doesn't name included.

### MetricsFilter

Keeps only the events or credit movements whose `field` matches.

- `field` (string, required) — A field of the view, as `GET /v1/metrics/views` lists it: a built-in such as `eventName`, `customer` or `product`, or, on `events`, a path into the event's payload such as `payload.team_id`. A payload path the views list doesn't name is accepted too. `credits` has `type`, `creditCurrency`, `customer`, `product`, `grantedBy`, `order`, `eventName` and `payload.<key>`, a field of the signal a spend paid for, and `amount`, which `sum`, `avg`, `min` and `max` take and a filter compares with `gt`, `gte`, `lt` or `lte`, but `groupBy` doesn't; and the related fields `customer.name`, `customer.externalId`, `customer.status`, `product.name`, `product.externalId`, `grantedBy.name`, `grantedBy.externalId`, `order.name` and `order.externalId`, each the current value of the record its ID field names. `events` also has `customer.name`, `customer.externalId`, `customer.status`, `product.name` and `product.externalId`, read through the event's `customer` and `product`. `metadata` has `eventName` and `creditCurrency` (filters only), `customer` and its `customer.name`, `customer.externalId` and `customer.status`, `payload.<key>`, folded across the entity's events, and `credits`, which only `sum`, `avg`, `min` and `max` take.
- `op` (enum, required) — `eq` and `ne` compare with one value; `in` and `notIn` with a list. `gt`, `gte`, `lt` and `lte` compare a number with one value, on a numeric field only: `payload.<key>` on every view, read by the number rule `sum` reads by, and `amount` on `credits`; a value that is no number matches none of them. `startsWith` keeps the values that begin with one non-empty value, exactly as written, case-sensitive, on `eventName`, `payload.<key>` (a number by its JSON text) and every related field the view takes (`customer.name`, …), by the record's current value; never on an ID field (`customer`, `product`, `grantedBy`, `order`). More values may be added.
  - Allowed values: `eq`, `ne`, `in`, `notIn`, `gt`, `gte`, `lt`, `lte`, `startsWith`
- `values` (list of string, required) — The values to compare with, 1 to 1000; exactly one for `eq`, `ne`, `gt`, `gte`, `lt`, `lte` and `startsWith`. A comparison's value is a decimal (`"10"`, `"-2.5"`, `"1e3"`); a `startsWith` value can't be empty. A `customer`, `product`, `grantedBy` or `order` value takes a Paid ID or your own ID; a related field's value (`customer.name`) is compared with the record's current value exactly, case included; a `creditCurrency` value takes the credit currency's `key`; a `type` value is `spend` or `grant`. A value may be the empty string, which is how a missing or non-scalar payload value groups, and on `credits` how `product` and `order` read on a grant and on a spend with no usage line or a deleted one, and how a related field reads where its record has no value or there is no record. A `grantedBy` value can't be empty: a pool no product made (a manual grant, a promotion) groups under `""` but can't be filtered on.

### MetricsKey

The entity the `metadata` view folds events into. Required with `view: "metadata"`, and `invalid_request` naming `key` with any other view.

- `field` (string, required) — The payload key whose value makes an entity, without the `payload.` prefix: a top-level key or a dotted path such as `run.id`, under the `events` view's rules for payload keys. An event whose value for it is missing, empty, null, an object or an array is not in the view; a number or boolean reads as its JSON text.
- `from` (list of string, optional) — The event names an entity is made from, 1 to 20, each once: its fields, its `eventName` set and its first time come from its events of these names, so they decide which entities exist; the filters decide which are kept. Leave it out for every name that carried `field` in the window.

### MetricsRankBy

Which of the request's aggregations ranks the groups, and which way. Groups are ranked by that figure over the whole window (an `avg` as the window's sum over its count), ties broken by the stored value, a null figure (an `avg`, `min` or `max` over no numbers) last either way: the first `groupLimit` are kept, and within a period rows come by that figure, then by group value, the remainder row last. Needs `groupBy`, and the pair must be one of `aggregations`; else `invalid_request` naming `rankBy`. Leave it out to rank by count, largest first.

- `aggregation` (enum, required) — How rows are combined: `count` counts them (events, credit movements, or entities on `metadata`), or with a `payload.<key>` field the rows whose value is a number; `sum`, `avg`, `min` and `max` take a numeric field (`payload.<key>` on every view, `amount` on `credits`, `credits` on `metadata`); `countDistinct` counts the distinct values of `field`, any field `groupBy` takes. A payload value is a number when it is a JSON number or a string holding one (`"42"`, `"1.5"`), of magnitude under 10^40; any other value is skipped, never an error. More values may be added.
  - Allowed values: `count`, `sum`, `countDistinct`, `avg`, `min`, `max`
- `direction` (enum, optional, default: desc) — `desc` (the default) keeps the groups with the largest figure, `asc` the smallest. On `credits` a spend is negative, so the biggest spenders by `sum` of `amount` are `asc`.
  - Allowed values: `desc`, `asc`
- `field` (string, optional) — The aggregation's field, as in `aggregations`: left out for a `count` of rows.

### MetricsRow

One group's figures for one period. Part of a result, not an object of its own.

- `group` (map from string to string, required) — One entry per `groupBy` field, in request order, holding the group's value as a string. `customer`, `product`, `grantedBy` and `order` hold Paid IDs, a related field such as `customer.name` the record's current value, except that events stored under an external ID or alias before the customer was known in Paid show that identifier, so one customer can appear under two values; a follow-up resolves them in the rollup. Every value is null on the remainder row. Empty when the request had no `groupBy`.
- `period` (NullableMetricsPeriod, required) — The span the row covers. Null when the request had no `granularity`: the row covers the whole window.
- `remainder` (boolean, required) — True on the row that folds every group past `groupLimit`, whose `group` values are all null. False on every other row, including a group whose field was absent on its events, which keeps the value the rollup stores for it (`""` or null).
- `values` (map from string to MetricsRowValues, required) — One entry per aggregation: `count`, or `<aggregation>_<field>` such as `sum_amount`. A count is a non-negative integer; a sum is a decimal string, and can be negative: on `credits`, a spend is negative and a grant or a reversal positive, as in `sum_credits` on `metadata`, `"0"` for an entity with no spend. A `countDistinct` is a non-negative integer, exact: how many distinct values of the field the row's events or movements hold, a missing or non-scalar payload value counting as one value, `""`, as it groups. On the remainder row it counts the distinct values of every folded group together, not the sum of their counts. A figure of a numeric field (`sum_payload.steps`, `avg_payload.steps`, `min_…`, `max_…`) is a decimal string rounded half away from zero to 6 places, over the rows whose value is a number, and `count_payload.steps` counts those rows. With none, `sum` is `"0"`, `count` is 0, and `avg`, `min` and `max` are null. `avg` is the exact sum over the count, rounded once; on the remainder row every figure is over the rows of every folded group together, never an average of averages.

### MetricsGroups

How many groups the window held. Null when the request had no `groupBy`.

- `kept` (integer, required) — Groups returned as their own rows.
- `truncated` (integer, required) — Groups past `groupLimit`, folded into the remainder row.

### MetricsResultKey

On `metadata`, the request's `key` with `from` resolved. Null on every other view.

- `field` (string, required) — The request's `key.field`.
- `from` (list of string, required) — The event names read, in byte order: the request's `key.from`, else every name that carried `field` in the window.

### MetricsWindow

The window the figures cover, as resolved from the request: what a query that left out `startsAt` or `endsAt` read.

- `endsAt` (datetime, required) — Exclusive end of the window read: the request's `endsAt`, else the first whole UTC hour after `asOf`.
- `startsAt` (datetime, required, nullable) — Inclusive start of the window read: the request's `startsAt`, else the first hour the view holds data for the account. Null when it holds none, and `data` is empty.

### ApiErrorObject

What went wrong, in the same shape for every /v1 error.

- `code` (string, required) — A stable, machine-readable code for this error. New codes may be added at any time. See [Errors](https://docs.paid.ai/preview/developers/api/errors) for what each one means and how to fix it. - `unauthorized`: The API key is missing, malformed, revoked or expired. - `session_revoked`: The session behind this token has been signed out. - `forbidden`: The credentials are valid but cannot access this account. - `insufficient_scope`: The API key's scopes do not cover this endpoint. - `user_required`: Only a person signed in to Paid can do this, not an API key: it sends email for the account or acts on its behalf. - `customer_key_forbidden`: A customer-scoped API key called an endpoint it cannot use. - `organization_required`: The request did not say which account it is for. - `auth_context_error`: Paid could not load the account for these credentials. - `invalid_version`: The API version is malformed or not a released version. - `rollback_window_expired`: The account tried to move its pinned version back after the rollback window closed. - `unknown_beta`: `Paid-Beta` names a beta that does not exist, or is malformed. - `beta_not_enabled`: The account is not enrolled in this private beta. - `beta_header_required`: A beta endpoint or field was used without opting in. - `invalid_idempotency_key`: `Idempotency-Key` is empty, longer than 255 characters, or not printable ASCII. - `idempotency_key_reused`: The `Idempotency-Key` was already used with a different request. - `idempotency_request_in_progress`: A request with this `Idempotency-Key` is still running. - `validation_error`: The request body or parameters failed validation. - `invalid_json`: The request body is not valid JSON. - `payload_too_large`: The request body exceeds 10 MB. - `resource_missing`: No resource or path matches the request. - `type_mismatch`: A polymorphic field's `type` doesn't match the sub-object sent with it, or more than one sub-object was sent. `param` names the field. - `reference_not_found`: A reference in the body or query string doesn't name a resource on the account. `param` names the field, e.g. `customer` or `lines[0].price`. - `resource_archived`: A resource the request names is archived, so it can't be used for this. `param` names the field; it's empty when the archived resource is the one in the path. - `resource_not_active`: A resource the request names isn't active: it's still a draft, has ended or was deactivated. `param` names the field. - `status_conflict`: The action can't run on the object in the path from its current `status`, e.g. activating an active order or releasing a captured hold. `message` names the status and the statuses the action needs. - `resource_in_use`: The resource can't be archived or changed this way while other resources still use it. `param` names the field when there is one. - `resource_exists`: A resource with this identifier (an `externalId`, `key` or alias) already exists on the account, ignoring letter case. `param` names the field. - `customer_mismatch`: A resource the request names belongs to a different customer than the one the request is for. `param` names the field. - `internal_error`: Something went wrong on Paid's side. - `currency_not_supported`: `currency` is not enabled on the account. - `currency_locked`: The customer has an order, so its `currency` cannot change. - `customer_has_active_orders`: The customer cannot be archived while it has an activating, active or paused order. - `parent_livemode_mismatch`: `parent` names a customer in the other mode: live for a test key, or test for a live key. - `parent_has_parent`: Parents are one level deep: the named parent has a parent of its own, or the customer being given a parent has children. - `parent_cycle`: `parent` names the customer itself, or, for a customer unit, the unit itself or a unit under it. - `has_active_children`: The customer cannot be archived while it is the `parent` of a customer that is not archived, or the customer unit while it has units under it that are not archived. - `tax_provider_not_connected`: Tax cannot be enabled while no tax provider is connected. - `mixed_tax_codes`: A prepaid commit taxed at purchase is scoped to products with different tax codes, so its invoice has no single code. - `tax_provider_unavailable`: The tax provider could not be reached, so the tax code could not be checked against its catalog. - `immutable_field`: An update tried to change a field that can't change after creation, such as a rate, a key or a reference. - `currency_mismatch`: An amount or reference isn't in the currency the request needs, such as an order's currency. - `limit_exceeded`: The request has more items than the resource allows, such as rates, adjustments, filters or outcomes. - `forfeit_confirmation_required`: Ending this would forfeit a remaining balance, and `forfeitRemaining` wasn't `true`. - `external_id_scopes_meter`: The product's `externalId` can't change while a meter is scoped to it, because the meter matches on that ID. - `percent_of_base_missing`: A percent-of line names prices in `of.lines` that aren't on the order. - `outcome_not_allowed`: `usage.outcome` was sent for an events meter, which has no outcomes. - `meter_not_priceable`: The meter can't be priced on its own: it has `groupBy`, or uses a dashboard-only feature. - `price_in_active_plan`: The price can't be archived while an active plan lists it. - `ambiguous_match`: Two rates match the same dimension values with equal specificity, so rating couldn't choose between them. - `meter_already_priced`: One measure would be priced by both a price and a rate card on the same order. - `no_common_currency`: The plan's lines share no currency. - `default_requires_upgrade_path`: `default: true` was sent on a plan with no `upgradePath`. - `plan_legacy`: The plan was converted from v2 without v1 prices, so it can't be used on a v1 order. - `upgrade_path_position_taken`: Another plan already has this `position` in the upgrade-path `group`. - `quantity_not_allowed`: A line has a `quantity`, but its price has no `unit` (a usage price or flat fee). - `quantity_out_of_range`: A `quantity` is outside the price's or line's `quantityLimits`. - `quantity_limits_wider_than_price`: A line's `quantityLimits` are wider than its price's. - `interval_mismatch`: A recurring price's interval neither divides the order's billing cycle evenly nor is a whole multiple of it. - `line_not_on_order`: An amendment change names a line from another order. - `no_material_changes`: The amendment's changes leave the order as it is. - `usage_billing_behind`: Usage for a past period hasn't been billed yet, so the usage line can't be replaced now. - `seats_exceed_quantity`: The new quantity is below the line's active seats. - `order_ambiguous`: Several orders share this `externalId`, so it can't name one of them. - `order_version_mismatch`: The order changed since the `expectedVersion` sent. - `preview_stale`: The order changed after the amendment was previewed. - `billing_unavailable`: Billing couldn't be reached to preview or apply the change. Nothing changed. - `commit_conflict`: The invoiced minimum overlaps another on the order in both time and scope. - `duplicate_outcome_key`: Two outcomes, or an outcome and `catchAll`, share a key. - `single_event_field_not_allowed`: A single-event meter sent a field only workflows or event aggregation use, such as `identifier`, `close` or `aggregation`. - `alias_unit_conflict`: `customer` is an alias of one unit and `customerUnit` names a unit outside its subtree. - `workflow_unit_conflict`: The event names a different customer unit from the open workflow it joins. - `incompatible_unit`: A strict meter reads a Quantity whose unit can't be converted to the meter's unit. - `unknown_provider`: Paid's model catalog doesn't know the inference provider. - `unknown_model`: Paid's model catalog doesn't know the model. - `range_too_large`: The range is longer than `granularity` allows. - `misaligned_range`: `startsAt` or `endsAt` doesn't fall on a bucket boundary in `timezone`. - `depth_exceeded`: The unit, or a moved subtree, would go below 16 levels. - `root_unit_immovable`: An update tried to move the customer's root unit. - `root_unit_always_billable`: A create or update tried to make the root unit non-billable. - `has_active_cap`: The unit can't be archived while it has an active spend cap. - `has_active_seat`: The unit can't be archived while it holds an active seat, or the customer is billed per seat, so its units can't be created, changed or archived. - `alias_held_by_draft_customer`: The alias value is a draft customer's external ID: usage sent under it before the alias existed made that draft. - `alias_system_managed`: The alias was made by Paid, when a customer's `externalId` changed or from a SalesBricks buyer, so it can't be updated, archived, unarchived or deleted. It has `systemManaged: true`. - `draft_has_billing`: The draft customer to merge has credit grants, pending spends or other billing postings. - `price_not_on_order`: `price` isn't on the order. - `price_not_seat_based`: `price` isn't a recurring price with `seats`. - `customer_unit_not_billable`: The customer unit has `effectiveBillable: false`, so it can't hold a seat. - `seat_limit_reached`: The seat line is full: a purchased line has `quantity` active seats, or an assigned line reached `quantityLimits.maximum`. - `unit_already_has_seat`: The unit already holds an active seat for this product. - `refill_rollover_conflict`: The grant sets both `refill` and `rollover`. - `credit_currency_key_reserved`: The credit currency `key` is an ISO 4217 currency code. - `insufficient_credits`: The customer's spendable balance in the credit currency doesn't cover the hold. Nothing was reserved. - `price_not_one_time`: The auto top-up's `price` isn't a one-time price. - `price_grants_mismatch`: The auto top-up's `price` doesn't grant the rule's credit currency. - `payment_method_required`: `collection: "chargeAutomatically"` was set, but there is no card to charge: the customer has no payment method on file, or the one named (or the default) is a bank transfer account. - `auto_top_up_conflict`: The customer already has an enabled auto top-up for this credit currency. - `invalid_request`: The request was rejected. - `not_found`: The requested resource does not exist. - `conflict`: The request conflicts with the resource's current state. - `rate_limited`: Too many requests in too short a time. - `api_error`: An unexpected error.
- `docUrl` (string, required) — A link to this code's entry on the errors page, or to the page itself for an undocumented code.
- `message` (string, required) — A human-readable explanation of what went wrong.
- `requestId` (string, required) — The ID of the request, also returned in the `Request-Id` header. Include it when contacting support.
- `type` (enum, required) — The category of error.
  - Allowed values: `invalid_request_error`, `authentication_error`, `permission_error`, `idempotency_error`, `rate_limit_error`, `api_error`
- `param` (string, optional) — The request field or header the error relates to, when there is one.

### NullableMetricsPeriod

The span the row covers. Null when the request had no `granularity`: the row covers the whole window.

- `endsAt` (datetime, required) — Exclusive end of the period. The last period ends at the window's `endsAt`.
- `startsAt` (datetime, required) — Inclusive start of the period. The first period starts at the window's `startsAt`.

### MetricsRowValues

- integer
- string

## Examples

**Request**

```json
{
  "view": "events"
}
```

**Response**

```json
{
  "object": "metricsResult",
  "asOf": "2026-11-09T17:02:11Z",
  "data": [
    {
      "group": {
        "customer": "cus_8HqL2v",
        "eventName": "workflow_run"
      },
      "period": {
        "endsAt": "2026-10-02T00:00:00Z",
        "startsAt": "2026-10-01T00:00:00Z"
      },
      "remainder": false,
      "values": {
        "count": 48213
      }
    }
  ],
  "granularity": "day",
  "groups": {
    "kept": 100,
    "truncated": 12
  },
  "key": {
    "field": "run_id",
    "from": [
      "workflow",
      "workflow_run"
    ]
  },
  "readFrom": "rollup",
  "view": "events",
  "window": {
    "endsAt": "2026-11-01T00:00:00Z",
    "startsAt": "2026-10-01T00:00:00Z"
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.paid.ai/v1/metrics/query"

payload = { "view": "events" }
headers = {
    "Paid-Beta": "metrics=v1",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.paid.ai/v1/metrics/query';
const options = {
  method: 'POST',
  headers: {
    'Paid-Beta': 'metrics=v1',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"view":"events"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.paid.ai/v1/metrics/query"

	payload := strings.NewReader("{\n  \"view\": \"events\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Paid-Beta", "metrics=v1")
	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.paid.ai/v1/metrics/query")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Paid-Beta"] = 'metrics=v1'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"view\": \"events\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.paid.ai/v1/metrics/query")
  .header("Paid-Beta", "metrics=v1")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"view\": \"events\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.paid.ai/v1/metrics/query', [
  'body' => '{
  "view": "events"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Paid-Beta' => 'metrics=v1',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.paid.ai/v1/metrics/query");
var request = new RestRequest(Method.POST);
request.AddHeader("Paid-Beta", "metrics=v1");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"view\": \"events\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Paid-Beta": "metrics=v1",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["view": "events"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.paid.ai/v1/metrics/query")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```