
## Aggregate tasks

`POST /v1/tasks/aggregate`

Count tasks with filtering and grouping. Numeric functions work on numeric task fields and on user fields of suitable types.

**Standard fields:**

- `status` — task status (for `groupBy`; numeric functions make no sense here — it is a categorical code). `groupBy: "status"` groups by the **actual stored** status — the `status` field value in the response, not the virtual meta-axis of `filter[status]`
- `priority` — priority (for `groupBy`)
- `responsibleId` — responsible person (for `groupBy`; an identifier)
- `groupId` — workgroup (for `groupBy`; an identifier)

All standard `aggregatable` fields are identifiers or categorical codes, so `count` and `groupBy` work on them. For numeric functions (`sum`/`avg`/`min`/`max`), suitable built-in candidates are `timeEstimate` (effort estimate in seconds), `timeSpentInLogs` (time actually spent, in seconds), or user fields. Those two fields are not accepted in `groupBy` — among the built-in ones, only the four listed above are available there.

> **Narrowing the result set by status.** To count only open/completed tasks, add `realStatus` (the actual status) to `filter`: `{"filter": {"realStatus": 2}}`. `filter[status]` here is also virtual (the `−1/−2/−3` meta-axis), not the number from the response. `realStatus` itself is `filter`/`sort` only — it is not a `groupBy` dimension: to break down by status use `groupBy: "status"` (which groups by the actual status, see above).

**User fields (UF):** UF fields of types `integer`, `double`, `money` — for numeric functions; UF 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 | Req. | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. Each element: `{ "field": "timeEstimate", "function": "sum" }`. Functions: `count`, `sum`, `avg`, `min`, `max`. For `count`, the field is `"*"`. Without the parameter — count only |
| `filter` | object | no | Filtering by `GET /v1/tasks/fields` fields.<br>[Filtering syntax](/docs/filtering). Example: `{"responsibleId": 1}` |
| `groupBy` | string \| string[] | no | Field or array of fields to group by (maximum 5). Accepts UF fields of any type |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/tasks/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "timeEstimate", "function": "sum" }
    ],
    "groupBy": "status"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/tasks/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [
      { "field": "timeEstimate", "function": "sum" }
    ],
    "groupBy": "status"
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/tasks/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [{ field: 'timeEstimate', function: 'sum' }],
    groupBy: 'status',
  }),
})

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

### JavaScript — OAuth application

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

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

> To group by several fields, pass an array: `"groupBy": ["status", "responsibleId"]` (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" }] }
```

How many tasks each responsible person has:

```json
{ "groupBy": "responsibleId" }
```

Sum over a numeric UF field by priority:

```json
{
  "aggregate": [{ "field": "UF_CRM_TASK_BUDGET", "function": "sum" }],
  "groupBy": "priority"
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of records matching the filter |
| `data.aggregates` | object | Aggregation results. Without `aggregate` — an empty object |
| `data.groups` | array | Groups (only with `groupBy`). Each element: grouping fields + `count` + `aggregates` |
| `data.meta.totalRecords` | number | Total number of records |
| `data.meta.recordsProcessed` | number | How many records were actually processed |
| `data.meta.truncated` | boolean | `true` if the 5000 limit was hit — aggregation and groups are built over the first 5000 records |
| `data.meta.groupTotal` | number | Total number of groups (only with `groupBy`) |
| `data.meta.groupsTruncated` | boolean | Whether the group list was limited by `groupLimit` |

## Response example

Response to the main request (`aggregate: [{field: "timeEstimate", function: "sum"}]` + `groupBy: "status"`):

```json
{
  "success": true,
  "data": {
    "count": 599,
    "aggregates": {
      "timeEstimate": { "sum": 54000 }
    },
    "groups": [
      { "status": "2", "count": 247, "aggregates": { "timeEstimate": { "sum": 18000 } } },
      { "status": "5", "count": 341, "aggregates": { "timeEstimate": { "sum": 32400 } } },
      { "status": "3", "count": 7,   "aggregates": { "timeEstimate": { "sum": 2400 } } },
      { "status": "4", "count": 4,   "aggregates": { "timeEstimate": { "sum": 1200 } } }
    ],
    "meta": {
      "totalRecords": 599,
      "recordsProcessed": 599,
      "truncated": false,
      "groupTotal": 4,
      "groupsTruncated": false
    }
  }
}
```

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

## Error response example

400 — non-existent field:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "Unknown field 'noSuchField'. Available: status, priority, responsibleId, groupId, UF_CRM_TASK_BUDGET, …"
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Unknown function or non-existent field — the message contains the list of allowed fields (standard + UF) |
| 400 | `INVALID_PARAMS` | A non-numeric UF field (`string`, `enumeration`, `date`) in `sum`/`avg`/`min`/`max` — the message names the type |
| 400 | `INVALID_PARAMS` | `groupBy` on a standard field outside the `aggregatable` list |
| 400 | `INVALID_PARAMS` | More than 5 fields in `groupBy` |
| 400 | `INVALID_PARAMS` | Reserved keywords in `groupBy`: `count`, `aggregates`, `meta`, `groups` |
| 403 | `SCOPE_DENIED` | The API key does not have the `tasks` scope |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |

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

## Known specifics

**`count` vs numeric functions.** `count` is computed in a single call and works at any volume. `sum`/`avg`/`min`/`max` load records page by page (maximum 5000) and compute on the API side. For result sets over 5000 — `meta.truncated: true`, aggregation over the first 5000. For exact counters on large result sets, use `count` or narrow the filter.

## See also

- [List tasks](./list.md)
- [Search tasks](./search.md)
- [Task fields](./fields.md)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
