
## Aggregate items

`POST /v1/items/:entityTypeId/aggregate`

Count, sum, average, minimum, and maximum over smart-process items with filtering and grouping. The smart process is set in the path via `entityTypeId` — the process type ID, which you can obtain through [GET /v1/smart-processes](/docs/entities/smart-processes/list).

**Standard fields:**

- `opportunity` — item amount (numeric aggregation makes sense)
- `categoryId` — category (for `groupBy`)
- `assignedById` — responsible person (for `groupBy`)
- `stageId` — stage (for `groupBy`)
- `createdBy` — created by (for `groupBy`)
- `updatedBy` — last modified by (for `groupBy`)

**User fields (UF):** UF field names are prefixed with the smart process's internal type number — `ufCrm<typeId>_*` (for example, `ufCrm7_1652689362`). This number is not equal to the `entityTypeId` from the path — get exact UF field names from the response of [`GET /v1/items/:entityTypeId/fields`](/docs/entities/items/fields) or from the `INVALID_PARAMS` error text, which lists your Bitrix24 account's available fields. Types `integer`, `double`, `money` are for numeric functions; a UF of any type is for `groupBy`. The main source of business data in smart processes is UF fields.

## Path parameters

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `entityTypeId` | number | yes | Smart process type ID. For custom smart processes — any positive integer from `GET /v1/smart-processes`. The values `1` (leads), `2` (deals), `3` (contacts), `4` (companies), `7` (quotes), `31` (invoices) are reserved — use the dedicated APIs: [/v1/deals](/docs/entities/deals/aggregate), [/v1/leads](/docs/entities/leads/aggregate), etc. |

## Request fields (body)

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. Each element: `{ "field": "opportunity", "function": "sum" }`. Functions: `count`, `sum`, `avg`, `min`, `max`. For `count`, the field is `"*"`. Without the array — only `count` |
| `filter` | object | no | Filter by `GET /v1/items/:entityTypeId/fields` fields. [Filtering syntax](/docs/filtering) |
| `groupBy` | string \| string[] | no | Field or array of fields to group by (maximum 5). Accepts standard fields and UF fields of any type |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/items/177/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "opportunity", "function": "sum" },
      { "field": "opportunity", "function": "avg" }
    ],
    "filter": { "categoryId": 7 },
    "groupBy": "stageId"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/items/177/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": { "categoryId": 7 },
    "groupBy": "stageId"
  }'
```

### JavaScript — personal key

```javascript
const entityTypeId = 177

const res = await fetch(`https://vibecode.bitrix24.com/v1/items/${entityTypeId}/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: { categoryId: 7 },
    groupBy: 'stageId',
  }),
})

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

### JavaScript — OAuth application

```javascript
const entityTypeId = 177

const res = await fetch(`https://vibecode.bitrix24.com/v1/items/${entityTypeId}/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: { categoryId: 7 },
    groupBy: 'stageId',
  }),
})

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

> To group by multiple fields, pass an array: `"groupBy": ["stageId", "categoryId"]` (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": "ufCrm7_1741091916816", "function": "sum" }],
  "groupBy": "ufCrm7_1652689362"
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of items matching the filter |
| `data.aggregates` | object | Aggregation results: `{ "opportunity": { "sum": 65911, "avg": 4707.92 } }` |
| `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 actually processed for aggregation |
| `data.meta.truncated` | boolean | `true` if more than 5000 records matched the filter |
| `data.meta.groupTotal` | number | Number of groups (only with `groupBy`) |
| `data.meta.groupsTruncated` | boolean | `true` if the group list was truncated |

## Response example

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

```json
{
  "success": true,
  "data": {
    "count": 14,
    "aggregates": {
      "opportunity": { "sum": 65911, "avg": 4707.92 }
    },
    "groups": [
      {
        "stageId": "DT177_7:NEW",
        "count": 8,
        "aggregates": { "opportunity": { "sum": 40000 } }
      },
      {
        "stageId": "DT177_7:SUCCESS",
        "count": 6,
        "aggregates": { "opportunity": { "sum": 25911 } }
      }
    ],
    "meta": {
      "totalRecords": 14,
      "recordsProcessed": 14,
      "truncated": false,
      "groupTotal": 2,
      "groupsTruncated": false
    }
  }
}
```

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

## Error response example

400 — reserved `entityTypeId` (for standard CRM entities):

```json
{
  "success": false,
  "error": {
    "code": "INVALID_DYNAMIC_PARAM",
    "message": "entityTypeId 2 has a dedicated API: use /v1/deals instead"
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_DYNAMIC_PARAM` | `entityTypeId` is not a positive integer or is reserved (1, 2, 3, 4, 7, 31) |
| 400 | `INVALID_PARAMS` | Invalid function name, non-existent field, or a non-numeric field in `sum`/`avg`/`min`/`max` |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |
| 403 | `SCOPE_DENIED` | The API key lacks the `crm` scope |

Full list of common API errors — [Errors](/docs/errors).

## Known specifics

**Without the `aggregate` array — only `count`.** If you do not pass `aggregate`, the method makes one fast call to Bitrix24 and returns the `count` of records matching the filter. Suitable for dashboard counters.

**Multiple aggregations in one request.** They can be combined in a single call: `[{ "field": "opportunity", "function": "sum" }, { "field": "opportunity", "function": "avg" }]`.

**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 — standard and custom, of any type. For example, `{ "filter": { "ufCrm7_1652689362": 1435 } }` returns the count of items with that UF value.

**5000-record limit.** Numeric aggregations load records page by page and compute on the Vibecode side. If more than 5000 records match the filter, the result is flagged with `meta.truncated: true` — only the first 5000 are taken. For an exact count use `count` (it works at any volume) or narrow the filter.

**Reserved `entityTypeId`.** The values `1` (leads), `2` (deals), `3` (contacts), `4` (companies), `7` (quotes), `31` (invoices) are served by dedicated APIs — use [/v1/deals/aggregate](/docs/entities/deals/aggregate), [/v1/leads/aggregate](/docs/entities/leads/aggregate), [/v1/contacts/aggregate](/docs/entities/contacts/aggregate), [/v1/companies/aggregate](/docs/entities/companies/aggregate), [/v1/quotes/aggregate](/docs/entities/quotes/aggregate), [/v1/invoices/aggregate](/docs/entities/invoices/aggregate).

## See also

- [Smart process list](/docs/entities/smart-processes/list)
- [Item list](/docs/entities/items/list)
- [Item search](/docs/entities/items/search)
- [Smart process fields](/docs/entities/items/fields)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
