## Aggregate services

`POST /v1/catalog-services/aggregate`

Counts the services of a product catalog with filtering and grouping by catalog section.

**Fields available for aggregation:**

- `iblockSectionId` — catalog section, for `groupBy`

A service has no numeric fields whose sum or average carries meaning. The `sum`, `avg`, `min`, `max` functions accept identifier fields — `id`, `iblockId`, `iblockSectionId`, `measure`, `vatId`, `createdBy`, `modifiedBy`, `type` — and the sort order `sort`. The main scenario is counting services with `count`, including by section.

## Request fields (body)

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `filter` | object | yes | Filtering by the fields of [`GET /v1/catalog-services/fields`](./fields.md). The `iblockId` key is required — the product catalog ID from [`GET /v1/catalogs`](/docs/entities/catalogs/list). To select the services of one section, pass `iblockSectionId` with an ID from [`GET /v1/catalog-sections`](/docs/entities/catalog-sections/list).<br>[Filtering syntax](/docs/filtering) |
| `aggregate` | array | no | Aggregations: `[{ "field": "sort", "function": "max" }]`. Functions: `sum`, `avg`, `min`, `max`, `count`. For `count`, the field is `"*"`. Without the parameter — `count` only |
| `groupBy` | string \| string[] | no | Field or array of fields to group by (up to 5). Value — `iblockSectionId` |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/catalog-services/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": { "iblockId": 25, "iblockSectionId": 281 },
    "groupBy": "iblockSectionId"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/catalog-services/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "filter": { "iblockId": 25, "iblockSectionId": 281 },
    "groupBy": "iblockSectionId"
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/catalog-services/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: { iblockId: 25, iblockSectionId: 281 },
    groupBy: 'iblockSectionId',
  }),
})

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

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/catalog-services/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    filter: { iblockId: 25, iblockSectionId: 281 },
    groupBy: 'iblockSectionId',
  }),
})

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

`groupBy` also accepts an array: `"groupBy": ["iblockSectionId"]`, up to 5 fields.

## Other scenarios

The blocks below are request bodies.

Number of services in a catalog — a body without `aggregate` or `groupBy`, the fastest request, with no records fetched. The `iblockId` filter is required here too:

```json
{ "filter": { "iblockId": 25 } }
```

Number of services in each catalog section — services without a section are collected into a group with `iblockSectionId: null`:

```json
{ "filter": { "iblockId": 25 }, "groupBy": "iblockSectionId" }
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Total number of services matching the filter |
| `data.aggregates` | object | Results of numeric functions: `{ "sort": { "max": 500 } }`. Without numeric functions — an empty object |
| `data.groups` | array | Groups — present only with `groupBy`. Each element: grouping fields + `count` + `aggregates` |
| `data.meta.totalRecords` | number | Total number of records |
| `data.meta.recordsProcessed` | number | Number of processed records (up to 5000). For a request without numeric functions or `groupBy` — `0` |
| `data.meta.truncated` | boolean | `true` 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 numeric functions, no records are fetched and the flag is always `false` |
| `data.meta.groupTotal` | number | Number of groups. Present only with `groupBy` |
| `data.meta.groupsTruncated` | boolean | `true` if the number of groups was limited. Present only with `groupBy` |

## Response example

```json
{
  "success": true,
  "data": {
    "count": 2,
    "aggregates": {},
    "groups": [
      {
        "iblockSectionId": 281,
        "count": 2,
        "aggregates": {}
      }
    ],
    "meta": {
      "totalRecords": 2,
      "recordsProcessed": 2,
      "truncated": false,
      "groupTotal": 1,
      "groupsTruncated": false
    }
  }
}
```

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

## Error response example

400 — a field outside the list available for grouping:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "groupBy field 'nonexistent' is not aggregatable on this entity. Available: iblockSectionId."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `MISSING_REQUIRED_FILTER` | The required `filter.iblockId` filter was not passed — checked before the Bitrix24 call, the message contains an example body |
| 400 | `UNKNOWN_FILTER_FIELD` | Filter on a field that a service does not have. The message contains the list of available fields |
| 400 | `INVALID_PARAMS` | The `groupBy` field is outside the available list — the message lists the allowed ones |
| 400 | `INVALID_PARAMS` | A numeric function over an unknown field — `Field '<name>' not found. Available numeric fields: ...` |
| 400 | `INVALID_PARAMS` | More than 5 fields passed in `groupBy` |
| 422 | `BITRIX_ERROR` | `filter.iblockId` holds the ID of an offer catalog rather than a product catalog (`productType is not allowed for this catalog`) |
| 403 | `SCOPE_DENIED` | The API key does not have the `catalog` scope |
| 401 | `MISSING_API_KEY` | The `X-Api-Key` header was not passed |
| 429 | `RATE_LIMITED` | Rate limit exceeded: 300 requests per minute per portal, all API keys of the portal share one limit. The exact value arrives in the `x-ratelimit-limit` header (the cap is divided across replicas). Retry after the delay in the `Retry-After` header |

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

## Known specifics

**`count` is resolved in one request, grouping is not.** `count` without `groupBy` is computed in a single call regardless of the size of the result set. `groupBy` and the `sum`, `avg`, `min`, `max` functions load records page by page — up to 5000 — and compute the values on the server side. If more than 5000 records match the filter, `meta.truncated` is `true`, and the groups are built over the first 5000. 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`.

**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](/docs/entity-api#aggregation-post-the-5000-record-ceiling).

## See also

- [List services](/docs/entities/catalog-services/list)
- [Search services](/docs/entities/catalog-services/search)
- [Service fields](/docs/entities/catalog-services/fields)
- [Catalog sections](/docs/entities/catalog-sections)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
