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 (forgroupBy)categoryId— funnel (forgroupBy)assignedById— assigned person (forgroupBy)sourceId— source (forgroupBy)
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 | 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 by GET /v1/deals/fields fields. Filtering syntax |
ParametergroupBy |
Typestring | string[] | Requiredno | DescriptionField or array of fields to group by (maximum 5). Allowed values — from the list above |
Examples
curl — personal key
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
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
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
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:
{ "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:
{
"aggregate": [{ "field": "ufCrmBudget", "function": "sum" }],
"groupBy": "ufCrmPriority"
}
Funnel summary — a single request with grouping by stage and a sum gives a breakdown from which the application side computes conversion to won deals:
{
"aggregate": [{ "field": "amount", "function": "sum" }],
"filter": { "categoryId": 0 },
"groupBy": "stageId"
}
In the response, data.count is the total number of deals in the funnel, data.groups is the breakdown by stage with sum and count. Stage identifiers depend on the funnel — you can get them from Fields. Conversion is computed from the groups without a separate request:
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 without proof of an end: 5000, the ceiling alone creates no 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 |
Response example
Response to the main request (aggregations + groupBy: "stageId"):
{
"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:
{
"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 |
| 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 count 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 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 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) returns422 AGGREGATION_LIMIT_EXCEEDEDwhentotal > 5000and fetches no records at all. Previously it fetched the first 5000 anyway — on a large funnel 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 scalarcategoryIdin the filter works on a funnel of any size: each stage count comes from a separate cheap count on the Bitrix24 side. The marker of such a response ismeta.aggregatePath: "fanout"withmeta.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.truncatedis thentrueand 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 ofdata.countand the sum of the stage counts. The size of the gap is reported indata.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 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.
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.
Legacy GET aggregate
Legacy GET /v1/{entity}/aggregate?op=sum&field=amount is deprecated; use POST for new callers. On GET, data.meta always contains recordsProcessed and truncated. A partial answer also carries data.truncated, groups[].truncated and total.truncated where those objects exist, plus meta.warnings with AGGREGATE_TRUNCATED. Known totalRecords and positive recordsShortfall are included; pageErrorSample contains only sanitized code/message when a page failed. Unknown totalRecords and recordsShortfall are omitted: an explicit paginator truncation signal remains true without either a measurable gap or a page error, even if a reported total equals the fetched count. GET count uses fetched rows and can be partial; POST normally obtains a complete total, but its missing-total recovery can also be marked incomplete. The existing GET limit of 10000 records still returns 422 AGGREGATION_LIMIT_EXCEEDED above the limit.
Example data for two fetched rows with an unknown overall count:
{
"op": "sum",
"field": "amount",
"value": 100,
"count": 2,
"truncated": true,
"meta": {
"recordsProcessed": 2,
"truncated": true,
"warnings": [
{
"code": "AGGREGATE_TRUNCATED",
"message": "This aggregate was computed over only the records in data.meta.recordsProcessed. Values and group counts describe a partial sample, not the full matching collection. Narrow the filter before treating the result as complete."
}
]
}
}