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

Aggregate leads

POST /v1/leads/aggregate

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

Standard fields:

  • opportunity — amount, canonical name, alias amount. Numeric functions and groupBy
  • stageId — status, canonical name, alias statusId. For groupBy
  • sourceId — source. For groupBy
  • assignedById — assignee. For groupBy
  • stageSemanticId — stage semantics: P — in progress, S — success, F — failure. For filter only. Grouping by this field returns 400 INVALID_PARAMS

User fields (UF): UF fields of type integer, double, money — for numeric functions; UF of any type — for groupBy. The full list of UF fields for a specific Bitrix24 account is returned in the INVALID_PARAMS error message 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 — only count
Parameterfilter Typeobject Requiredno DescriptionFiltering by GET /v1/leads/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

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

curl — OAuth application

Terminal
curl -X POST "https://vibecode.bitrix24.com/v1/leads/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": { "sourceId": "WEB" },
    "groupBy": "statusId"
  }'

JavaScript — personal key

javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/leads/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: { sourceId: 'WEB' },
    groupBy: 'statusId',
  }),
})

const { success, data } = await res.json()
console.log('Total leads:', data.count)
console.log('By status:', data.groups)

JavaScript — OAuth application

javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/leads/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: { sourceId: 'WEB' },
    groupBy: 'statusId',
  }),
})

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

To group by multiple fields, pass an array: "groupBy": ["statusId", "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:

JSON
{
  "aggregate": [{ "field": "UF_CRM_BUDGET", "function": "sum" }],
  "groupBy": "UF_CRM_PRIORITY"
}

Response fields

Field Type Description
Fieldsuccess Typeboolean DescriptionAlways true on success
Fielddata.count Typenumber DescriptionTotal number of records matching the filter
Fielddata.aggregates Typeobject DescriptionAggregation results: { "amount": { "sum": 500000, "avg": 5000 } }
Fielddata.groups Typearray DescriptionGroups (only with groupBy). Each element: grouping fields + count + aggregates
Fielddata.meta.totalRecords Typenumber DescriptionTotal number of records matching the filter
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 data.count promised — including when more than 5000 matched the filter — or the slice was cut short by a sub-page error. 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: "statusId"):

JSON
{
  "success": true,
  "data": {
    "count": 100,
    "aggregates": {
      "amount": { "sum": 500000, "avg": 5000 }
    },
    "groups": [
      {
        "statusId": "NEW",
        "count": 60,
        "aggregates": { "amount": { "sum": 300000 } }
      },
      {
        "statusId": "CONVERTED",
        "count": 40,
        "aggregates": { "amount": { "sum": 200000 } }
      }
    ],
    "meta": {
      "totalRecords": 100,
      "recordsProcessed": 100,
      "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, companyId, contactId, amount, opportunity, assignedById, createdBy."
  }
}

Errors

HTTP Code Description
HTTP400 CodeINVALID_PARAMS DescriptionUnknown function in aggregate[].function. Allowed: count, sum, avg, min, max
HTTP400 CodeINVALID_PARAMS DescriptionNon-existent field in aggregate[].field. The message lists the allowed numeric fields, both standard and user-defined
HTTP400 CodeINVALID_PARAMS DescriptionNon-numeric field in sum, avg, min, or max. The message names the field type
HTTP400 CodeINVALID_PARAMS DescriptionA groupBy field outside the allowed list, such as stageSemanticId or a non-existent name. The message lists the allowed fields
HTTP400 CodeINVALID_PARAMS DescriptionMore than 5 fields in groupBy
HTTP400 CodeINVALID_PARAMS DescriptiongroupBy contains a reserved name: count, aggregates, meta, groups
HTTP400 CodeUNKNOWN_FILTER_FIELD DescriptionNon-existent field in filter. The message lists the allowed fields
HTTP401 CodeTOKEN_MISSING DescriptionThe API key has no configured tokens
HTTP403 CodeSCOPE_DENIED DescriptionThe API key does not have 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 vs numeric functions. count is computed with a single call to Bitrix24 regardless of data volume. The sum/avg/min/max functions load records page by page (maximum 5000) and compute 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 not the only reason for this marker: it also appears when fewer records were read than data.count promised, and the size of the gap is reported in data.meta.recordsShortfall.

Money fields. UF fields of type money are stored in the "amount|currency" format ("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 — standard or user-defined, of any type. For example, { "filter": { "ufCrm_1234": "value" } } returns the count of leads with that UF value.

The truncation marker travels with the number itself. When a response arrives with meta.truncated: true, the marker truncated: true sits inside every field object in data.aggregates and on every element of data.groups, and data.meta.warnings gains a warning with the code AGGREGATE_TRUNCATED. A client that reads only the number itself therefore sees that it was computed over only some of the records. None of these markers appear on a complete response. Full details — Aggregation POST — the 5000-record ceiling.

See also