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

Aggregate invoices

POST /v1/invoices/aggregate

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

Standard fields:

  • opportunity — invoice amount (suitable for numeric aggregation)
  • stageId — stage (for groupBy)
  • assignedById — assignee (for groupBy)

User fields (UF): numeric functions accept UF fields of types integer, double, money, and groupBy accepts UF of any type. 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)

Field Type Required Description
Fieldaggregate Typearray Requiredno DescriptionArray of aggregations. Each element: { "field": "opportunity", "function": "sum" }. Functions: count, sum, avg, min, max. For count, the field is "*". If the array is omitted, only count is returned
Fieldfilter Typeobject Requiredno DescriptionFiltering. The accepted names are listed in the 400 UNKNOWN_FILTER_FIELD error text — not every field from GET /v1/invoices/fields can be filtered on. Filtering syntax
FieldgroupBy 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/invoices/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "opportunity", "function": "sum" },
      { "field": "opportunity", "function": "avg" }
    ],
    "filter": { "assignedById": 1 },
    "groupBy": "stageId"
  }'

curl — OAuth application

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

JavaScript — personal key

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

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

JavaScript — OAuth application

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

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

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

Other scenarios

The blocks below are request bodies.

Counting records: count with field "*" is the fastest request and fetches no 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_TAX", "function": "sum" }],
  "groupBy": "UF_CRM_PAYMENT_METHOD"
}

Response fields

Field Type Description
Fieldsuccess Typeboolean DescriptionAlways true on success
Fielddata Typeobject DescriptionThe aggregation result. Its fields are the data.* rows below
Fielddata.count Typenumber DescriptionTotal number of records matching the filter
Fielddata.aggregates Typeobject DescriptionAggregation results: { "opportunity": { "sum": 120000, "avg": 2200 } }
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
Fielddata.meta.groupTotal Typenumber DescriptionNumber of groups produced. Present when groupBy is used
Fielddata.meta.groupsTruncated Typeboolean Descriptiontrue if there are more groups than were returned. Present when groupBy is used

Response example

Response to the main request — aggregations and groupBy: "stageId":

JSON
{
  "success": true,
  "data": {
    "count": 57,
    "aggregates": {
      "opportunity": { "sum": 121850.2, "avg": 2137.722807017544 }
    },
    "groups": [
      {
        "stageId": "DT31_5:N",
        "count": 54,
        "aggregates": { "opportunity": { "sum": 121620.2, "avg": 2252.225925925926 } }
      },
      {
        "stageId": "DT31_5:P",
        "count": 3,
        "aggregates": { "opportunity": { "sum": 230, "avg": 76.66666666666667 } }
      }
    ],
    "meta": {
      "totalRecords": 57,
      "recordsProcessed": 57,
      "truncated": false,
      "groupTotal": 2,
      "groupsTruncated": false
    }
  }
}

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

Error response example

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

JSON
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "Field 'foo' not found. Available numeric fields: id, categoryId, assignedById, contactId, companyId, opportunity, taxValue, mycompanyId, webformId, createdBy, lastActivityBy, updatedBy, movedBy. User-defined: ufCrm_619F45A0AF6DB (money), ufCrm_619F45A16FECA (money), ufCrm_619F45A18C152 (double), ufCrm_619F45A719813 (integer), ..."
  }
}

Errors

HTTP Code Description
HTTP400 CodeINVALID_PARAMS DescriptionParsing of the aggregate array and the groupBy field: invalid function name, non-existent field in aggregate, non-numeric field in sum/avg/min/max, groupBy on a non-aggregatable field, or more than 5 fields in groupBy
HTTP400 CodeUNKNOWN_FILTER_FIELD DescriptionParsing of filter: a filter on a field the invoice does not have. The error text lists the allowed names. This is a different branch from INVALID_PARAMS above, which covers the contents of aggregate and groupBy
HTTP401 CodeTOKEN_MISSING DescriptionThe API key has no configured tokens
HTTP403 CodeSCOPE_DENIED DescriptionThe API 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 vs numeric functions. count is computed with a single call to Bitrix24 regardless of data volume. The sum/avg/min/max functions fetch 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 format "amount|currency" — for instance "1500|USD". Aggregation extracts the numeric part automatically, so there is no need to parse the string on your side.

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