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 (suitable for numeric aggregation)
  • stageId — stage (for groupBy)
  • categoryId — funnel (for groupBy)
  • assignedById — responsible person (for groupBy)
  • sourceId — source (for groupBy)
  • currency — deal currency (for groupBy). Currency list: GET /v1/currencies

User fields (UF): fields of type integer, double or money work with numeric functions; fields of any type work with 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 Required Description
Parameteraggregate Typearray Requiredno DescriptionArray of aggregations. Each element: { "field": "amount", "function": "sum" }. Functions: count, sum, avg, min, max. For count, the field is "*". Without the array — count only
Parameterfilter Typeobject Requiredno DescriptionFilter on the fields returned by GET /v1/deals/fields. Filtering syntax
ParametergroupBy Typestring | string[] Requiredno DescriptionField or array of fields to group by (maximum 5). Allowed values are the fields listed 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 application

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 funnel:', data.count)
console.log('By stage:', data.groups)

JavaScript — OAuth application

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

The blocks below are request bodies.

Count records — count with the 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"
}

Funnel summary — a single request with grouping by stage and a sum gives a breakdown from which your application 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 funnel, and data.groups is the breakdown by stage with sum and count. Stage identifiers depend on the funnel — you can get them from Deal 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 funnel: ${total}, won: ${won}, conversion: ${conversion}%`)

Response fields

Field Type Description
Fieldsuccess Typeboolean DescriptionAlways true on success
Fielddata.count Typenumber DescriptionExact after a complete probe or count walk; an observed lower bound if that walk stops early
Fielddata.truncated Typeboolean DescriptionPresent only for an incomplete count recovery, always true
Fielddata.aggregates Typeobject DescriptionAggregation results: { "amount": { "sum": 100000, "avg": 2439 } }
Fielddata.groups Typearray DescriptionGroups (only with groupBy). Each element: grouping fields + count + aggregates
Fielddata.meta.totalRecords Typenumber DescriptionSame value as data.count: exact after a complete count, a lower bound after an interruption
Fielddata.meta.recordsProcessed Typenumber DescriptionHow many records were processed for numeric aggregations (maximum 5000)
Fielddata.meta.truncated Typeboolean Descriptiontrue 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. Without groupBy or a numeric function, the flag can still be true if the missing-total count walk stops early
Fielddata.meta.pageErrorSample Typeobject DescriptionPresent after a failed record page or count page. A count failure contains only the safe AGGREGATE_COUNT_PAGE_FAILED code and an offset, never the Bitrix24 exception text
Fielddata.meta.countWalkLimit Typenumber DescriptionPresent only after 100 full count pages with no confirmed end; the value is 5000. The ceiling alone does not create pageErrorSample, but a later record-page failure can add one
Fielddata.meta.warnings Typearray DescriptionContains AGGREGATE_TRUNCATED when truncated; for an incomplete count it explains that count is a lower bound. Independently of truncation, contains AGGREGATE_MIXED_CURRENCIES when sum, avg, min or max reads a field stored in the record currency over records in more than one currency while groupBy names no currency field

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: id, amount, categoryId, companyId, mycompanyId, contactId, assignedById, createdBy, probability, webformId, updatedBy, movedBy, repeatSaleSegmentId, leadId, quoteId, lastActivityBy, taxValue, receivedAmount, lostAmount."
  }
}

Errors

HTTP Code Description
HTTP400 CodeINVALID_PARAMS DescriptionInvalid 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
HTTP401 CodeTOKEN_MISSING DescriptionAPI key has no configured tokens
HTTP403 CodeSCOPE_DENIED DescriptionAPI key lacks the crm scope
HTTP422 CodeAGGREGATION_LIMIT_EXCEEDED DescriptionMore than 5000 records match the filter and the request needs rows (numeric functions or groupBy). Returned only when one of the large-funnel modes is on for the account (see "Known specifics"). The error text lists what to do next
HTTP429 CodeRATE_LIMITED DescriptionRate limit exceeded: 300 requests per minute per portal. All API keys of the portal share one limit. The current limit is returned in the x-ratelimit-limit header. Retry after the delay in the Retry-After header

For the full list of common API errors, see Errors.

Known specifics

count and numeric functions — the difference. count without groupBy normally comes from one Bitrix24 probe; if the method omits a usable total, the platform walks count pages up to 5000 rows. On a failed or malformed page, data.meta.pageErrorSample carries AGGREGATE_COUNT_PAGE_FAILED; after 5000 rows without proof of an end, data.meta.countWalkLimit is 5000. The response remains 200, but data.truncated and meta.truncated are true, and count is a lower bound. 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 counts on large result sets, use count or narrow the filter; check meta.truncated before treating the number as exact. 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 in the stage-count 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 funnel: 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. The error text lists what to do next.
  • Per-stage counts without reading rows. groupBy: ["stageId"] with a scalar categoryId in the filter, or groupBy: ["stageSemanticId"] with any categoryId condition or none, works on a result set 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.

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 funnel'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.

Amounts in different currencies. sum, avg, min and max over amount and taxValue do not convert currencies: deals in USD and EUR yield one number that mixes both, and the response carries an AGGREGATE_MIXED_CURRENCIES warning in data.meta.warnings. "groupBy": "currency" gives the total per currency — the response carries a separate group for each currency and no warning. The account accounting-currency fields receivedAmount and lostAmount never raise the warning: they are already expressed in one currency.

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