## Aggregate calendar events

`POST /v1/calendar-events/aggregate`

Counts the events of one calendar over a period and sums their numeric fields, for example the total duration of an employee's meetings over a year. The calendar and the period are set inside the `filter` object.

## Request fields (body)

| Field | Type | Required | Description |
|------|-----|:-----:|---------|
| `filter` | object | yes | The calendar and the period to select. Accepts only `type`, `ownerId`, `from`, `to`, `section`. A field outside this set returns `400 UNSUPPORTED_FILTER` |
| `filter.type` | string | yes | Calendar type: `user`, `group`, `company_calendar` |
| `filter.ownerId` | number | yes | Calendar owner ID. For `type=user` — the employee ID from `GET /v1/users`, for `type=group` — the workgroup ID |
| `filter.from` | string | no | Start of the event selection period (ISO 8601). Without `from` and `to`, the same period applies as for the [event list](/docs/entities/calendar-events/list): from one month back to three months ahead |
| `filter.to` | string | no | End of the event selection period (ISO 8601) |
| `filter.section` | number | no | Calendar section ID — the value of the event's `sectionId` field. Accepted as a single number. An array returns `400 UNSUPPORTED_FILTER` |
| `aggregate` | array | no | Array of `{ "field": "<field>", "function": "<function>" }` expressions, up to 5. Functions: `count`, `sum`, `avg`, `min`, `max`. `count` accepts only `"field": "*"`. Numeric functions accept fields of type `number`: of these, `durationSeconds` contains the duration; the rest are identifiers (`id`, `ownerId`, `sectionId`, `createdBy` and others). Without the parameter, only `count` is returned |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/calendar-events/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": {
      "type": "user",
      "ownerId": 1,
      "from": "2026-01-01",
      "to": "2026-12-31"
    },
    "aggregate": [
      { "field": "durationSeconds", "function": "sum" }
    ]
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/calendar-events/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": {
      "type": "user",
      "ownerId": 1,
      "from": "2026-01-01",
      "to": "2026-12-31"
    },
    "aggregate": [
      { "field": "durationSeconds", "function": "sum" }
    ]
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/calendar-events/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: {
      type: 'user',
      ownerId: 1,
      from: '2026-01-01',
      to: '2026-12-31',
    },
    aggregate: [
      { field: 'durationSeconds', function: 'sum' },
    ],
  }),
})

const { success, data } = await res.json()
console.log('Events:', data.count, 'hours:', data.aggregates.durationSeconds.sum / 3600)
```

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/calendar-events/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: {
      type: 'user',
      ownerId: 1,
      from: '2026-01-01',
      to: '2026-12-31',
    },
    aggregate: [
      { field: 'durationSeconds', function: 'sum' },
    ],
  }),
})

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

## Other scenarios

The blocks below are request bodies.

Number of events in an employee's calendar over the default period, without loading the records:

```json
{ "filter": { "type": "user", "ownerId": 1 } }
```

Number of events in one calendar section over a year:

```json
{ "filter": { "type": "user", "ownerId": 1, "from": "2026-01-01", "to": "2026-12-31", "section": 3 } }
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Number of calendar events over the period |
| `data.aggregates` | object | Results of the numeric functions: the key is the field name, inside is the value for each function, for example `durationSeconds.sum`. An empty object if the `aggregate` array is not passed |
| `data.meta.totalRecords` | number | Total number of records matching the filter |
| `data.meta.recordsProcessed` | number | Number of records read. `0` when only `count` is computed |
| `data.meta.truncated` | boolean | `true` if the numbers are not computed over all records matching the filter: fewer records were read than `data.count` promised — including when more than 5000 matched the filter — or the slice was cut off by a subpage error. The size of the shortfall is reported in `data.meta.recordsShortfall`, the cut-off slice in `data.meta.pageErrorSample`. Always present, `false` on a complete response. If the request has no numeric functions, no records are loaded and the flag is always `false` |

## Response example

Sum of event durations over a year:

```json
{
  "success": true,
  "data": {
    "count": 6,
    "aggregates": {
      "durationSeconds": { "sum": 104400 }
    },
    "meta": {
      "totalRecords": 6,
      "recordsProcessed": 6,
      "truncated": false
    }
  }
}
```

## Error response example

400 — the required `type` and `ownerId` are not passed in `filter`:

```json
{
  "success": false,
  "error": {
    "code": "MISSING_REQUIRED_PARAMS",
    "message": "POST /v1/calendar-events/aggregate requires filter params: type, ownerId. Example body: { \"filter\": {\"type\":\"...\",\"ownerId\":\"...\"} }"
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `MISSING_REQUIRED_PARAMS` | `filter` lacks `type` and/or `ownerId`, or the value is empty or passed as an array or an object. These fields at the top level of the body, outside `filter`, do not count. `message` lists the missing fields |
| 400 | `UNSUPPORTED_FILTER` | `filter` contains a field outside the `type`, `ownerId`, `from`, `to`, `section` set, or `section` is passed as an array |
| 400 | `INVALID_PARAMS` | Unknown aggregation function. The message lists the allowed ones |
| 400 | `INVALID_PARAMS` | Empty `aggregate` array |
| 400 | `INVALID_PARAMS` | More than 5 expressions in `aggregate` |
| 400 | `INVALID_PARAMS` | `count` with a field other than `"*"` |
| 400 | `INVALID_PARAMS` | Numeric function on a field whose type is not `number`. The message names the field type |
| 400 | `INVALID_PARAMS` | Numeric function on a field that events do not have. The message lists the available numeric fields |
| 400 | `INVALID_PARAMS` | Numeric function without a field or with the `"*"` field |
| 400 | `INVALID_PARAMS` | `groupBy` is passed — calendar events have no fields to group by |
| 403 | `SCOPE_DENIED` | The API key does not have the `calendar` scope |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |
| 429 | `RATE_LIMITED` | Request limit exceeded: 300 per minute per Bitrix24 account. All API keys of the account 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](/docs/errors).

## Known specifics

**The count matches the list.** Without `from`, `to`, and `section`, `data.count` equals `meta.total` of the [event list](/docs/entities/calendar-events/list) for the same `type` and `ownerId`: both count over the same default period. There is no grouping, so a count across several sections or employees takes a separate request per section or per calendar owner.

**A nonexistent calendar returns zero, not an error.** An unknown `type` value or a nonexistent `ownerId` returns `200` with `count: 0`. A zero count does not tell an empty calendar from a mistake in the `type` + `ownerId` pair — check the pair with an [event list](/docs/entities/calendar-events/list) request.

**Numeric functions are computed over the records read.** `count` without numeric functions is returned without loading the records. `sum`, `avg`, `min`, `max` read events page by page, at most 5000. When the response comes with `meta.truncated: true`, a `truncated: true` marker sits inside each field's object in `data.aggregates`, and a warning with the `AGGREGATE_TRUNCATED` code is added to `data.meta.warnings`. Full details — [Aggregation POST — the 5000-record ceiling](/docs/entity-api#aggregation-post-the-5000-record-ceiling).

## See also

- [Event list](/docs/entities/calendar-events/list)
- [Search events](/docs/entities/calendar-events/search)
- [Event fields](/docs/entities/calendar-events/fields)
- [Limits and optimization](/docs/optimization)
