For AI agents: markdown of this page — /docs-content-en/entities/deals/aggregate.md documentation index — /llms.txt

Aggregate deals

POST /v1/deals/aggregate

Count, sum, average, minimum and maximum over deals with filtering and grouping.

Standard fields:

  • amount — deal amount (numeric aggregation makes sense)
  • stageId — stage (for groupBy)
  • categoryId — pipeline (for groupBy)
  • assignedById — assigned person (for groupBy)
  • sourceId — source (for groupBy)

User fields (UF): fields of types integer, double, money — for numeric functions, fields of any type — for groupBy. The full list of UF fields for a specific Bitrix24 account is returned in the INVALID_PARAMS error text if you pass a non-existent name.

Request fields (body)

Parameter Type Req. Description
aggregate array no Array of aggregations. Each element: { "field": "amount", "function": "sum" }. Functions: count, sum, avg, min, max. For count, the field is "*". Without the array — count only
filter object no Filter by GET /v1/deals/fields fields. Filtering syntax
groupBy string | string[] no Field or array of fields to group by (maximum 5). Allowed values — from the list above

Examples

curl — personal key

Terminal
curl -X POST "https://vibecode.bitrix24.com/v1/deals/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "amount", "function": "sum" },
      { "field": "amount", "function": "avg" }
    ],
    "filter": { "categoryId": 0 },
    "groupBy": "stageId"
  }'

curl — OAuth app

Terminal
curl -X POST "https://vibecode.bitrix24.com/v1/deals/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "amount", "function": "sum" },
      { "field": "amount", "function": "avg" }
    ],
    "filter": { "categoryId": 0 },
    "groupBy": "stageId"
  }'

JavaScript — personal key

javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/deals/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [
      { field: 'amount', function: 'sum' },
      { field: 'amount', function: 'avg' },
    ],
    filter: { categoryId: 0 },
    groupBy: 'stageId',
  }),
})

const { success, data } = await res.json()
console.log('Total deals in pipeline:', data.count)
console.log('By stage:', data.groups)

JavaScript — OAuth app

javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/deals/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [
      { field: 'amount', function: 'sum' },
      { field: 'amount', function: 'avg' },
    ],
    filter: { categoryId: 0 },
    groupBy: 'stageId',
  }),
})

const { success, data } = await res.json()

To group by several fields, pass an array: "groupBy": ["stageId", "sourceId"] (maximum 5).

Other scenarios

Count records — count with field "*", the fastest request without fetching records. Without the aggregate array the result is the same:

JSON
{ "aggregate": [{ "field": "*", "function": "count" }] }

Working with user fields (UF) — sum over a UF + grouping by another UF. The field name comes from the GET /v1/deals/fields schema, and any other spelling returns 400 INVALID_PARAMS with the list of available fields:

JSON
{
  "aggregate": [{ "field": "ufCrmBudget", "function": "sum" }],
  "groupBy": "ufCrmPriority"
}

Pipeline summary — a single request with grouping by stage and a sum gives a breakdown from which the application side computes conversion to won deals:

JSON
{
  "aggregate": [{ "field": "amount", "function": "sum" }],
  "filter": { "categoryId": 0 },
  "groupBy": "stageId"
}

In the response, data.count is the total number of deals in the pipeline, data.groups is the breakdown by stage with sum and count. Stage identifiers depend on the pipeline — you can get them from Fields. Conversion is computed from the groups without a separate request:

javascript
const total = data.count
const won = data.groups.find(g => g.stageId === 'WON')?.count ?? 0
const conversion = total ? Math.round((won / total) * 100) : 0
console.log(`Deals in pipeline: ${total}, won: ${won}, conversion: ${conversion}%`)

Response fields

Field Type Description
success boolean Always true on success
data.count number Total number of records matching the filter
data.aggregates object Aggregation results: { "amount": { "sum": 100000, "avg": 2439 } }
data.groups array Groups (only with groupBy). Each element: grouping fields + count + aggregates
data.meta.totalRecords number Total number of records matching the filter
data.meta.recordsProcessed number How many records were processed for numeric aggregations (maximum 5000)
data.meta.truncated boolean true when the numbers were computed over only some of the records that match the filter: fewer records were read than the response promised — including when more than 5000 matched the filter — or the slice was cut short by a sub-page error. What the response promised is data.count, and in the stage-count mode the larger of data.count and the sum of the stage counts. The size of the gap is reported in data.meta.recordsShortfall, the interrupted slice in data.meta.pageErrorSample. Always present, and false on a complete response. If the request has neither groupBy nor a numeric function, no records are fetched and the flag is always false

Response example

Response to the main request (aggregations + groupBy: "stageId"):

JSON
{
  "success": true,
  "data": {
    "count": 41,
    "aggregates": {
      "amount": { "sum": 100000, "avg": 2439 }
    },
    "groups": [
      {
        "stageId": "NEW",
        "count": 25,
        "aggregates": { "amount": { "sum": 60000 } }
      },
      {
        "stageId": "WON",
        "count": 16,
        "aggregates": { "amount": { "sum": 40000 } }
      }
    ],
    "meta": {
      "totalRecords": 41,
      "recordsProcessed": 41,
      "truncated": false
    }
  }
}

Without groupBy the data.groups field is absent from the response.

Error response example

400 — invalid function name, non-existent field, or groupBy over a non-aggregatable field:

JSON
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "Field 'foo' not found. Available numeric fields: amount, stageId, categoryId, assignedById, sourceId"
  }
}

Errors

HTTP Code Description
400 INVALID_PARAMS Invalid function name, non-existent field, non-numeric field in sum/avg/min/max, groupBy over a non-aggregatable field, or more than 5 fields in groupBy
401 TOKEN_MISSING API key has no configured tokens
403 SCOPE_DENIED API key lacks the crm scope
429 RATE_LIMITED Rate limit exceeded: 300 requests per minute per portal, all API keys of the portal share one limit. The exact value arrives in the x-ratelimit-limit header (the cap is divided across replicas). Retry after the delay in the Retry-After header

Full list of common API errors — Errors.

Known specifics

count and numeric functions — the difference. count without groupBy is computed with a single call to Bitrix24 regardless of data volume. The functions sum/avg/min/max fetch records page by page (maximum 5000) and compute the result on the Vibecode side — if more than 5000 records match the filter, meta.truncated will be true and the aggregation runs over the first 5000. For exact counts on large result sets, use count or narrow the filter. The ceiling is shared by every entity — Aggregation POST — the 5000-record ceiling. The ceiling is not the only reason for this marker: it also appears when fewer records were read than the response promised, and under the per-stage counting mode the promise is the larger of data.count and the sum of the stage counts. The size of the gap is reported in data.meta.recordsShortfall.

Large pipeline: two modes, switched on per account by a platform administrator.

Both are off by default. While they are off, the behavior is exactly as described above.

  • Refusal instead of truncation. A request that needs rows to answer (numeric functions and/or groupBy) returns 422 AGGREGATION_LIMIT_EXCEEDED when total > 5000 and fetches no records at all. Previously it fetched the first 5000 anyway — on a large pipeline that fetch did not finish and the request timed out. The error text lists what to do next.
  • Per-stage counts without reading rows. groupBy: ["stageId"] or ["stageSemanticId"] with a scalar categoryId in the filter works on a pipeline of any size: each stage count comes from a separate cheap count on the Bitrix24 side. The marker of such a response is meta.aggregatePath: "fanout" with meta.recordsProcessed: 0: no rows were read at all, so the counts are exact. Numeric functions per stage stay available while the combined group size fits in 5000 — but those do need rows, and such a response may come back truncated: meta.truncated is then true and the numbers carry the marker. The stage counts themselves stay exact — they come from a probe, not from the rows that were read. The ceiling is not the only reason for this marker: it also appears when fewer records were read than the response promised, and under the per-stage counting mode the promise is the larger of data.count and the sum of the stage counts. The size of the gap is reported in data.meta.recordsShortfall.

meta.stageCountDelta appears only in a response with per-stage counts: the difference between the overall total and the sum of the stage counts. Zero means the split is complete. A non-zero value means some records did not make it into the split — either records changed between the counts, or some of them sit in a stage that the pipeline's stage directory no longer lists. The stage counts and count stay exact regardless: count is always the overall total, never the sum of the groups. The numeric aggregates in such a response, however, are computed over fewer rows, so it arrives with meta.truncated: true and the markers next to the numbers.

money fields. UF fields of type money are stored in the format "amount|currency" ("1500|USD") — the aggregate extracts the numeric part automatically, so you can sum them without parsing.

Filtering by UF works. In filter you can pass any fields — both standard and user fields, of any type. For example, { "filter": { "ufCrm_1234": "value" } } returns the number of deals with this UF value.

See also