## Aggregate basket item properties

`POST /v1/basket-item-properties/aggregate`

Counts basket item properties by filter and grouping fields, and calculates the sum, average, minimum, and maximum of numeric fields.

## Standard fields

| Field | Purpose |
|---|---|
| `basketId` | Basket item ID. Source: [`GET /v1/basket-items`](/docs/entities/basket-items/list). For `groupBy` and numeric functions |
| `code` | Property symbolic code — for `groupBy` |
| `sort` | Sort order — for `sum`, `avg`, `min`, `max` |
| `id` | Property ID. Source: [`GET /v1/basket-item-properties`](/docs/entities/basket-item-properties/list). A numeric field |

Fields for `groupBy` are listed in `data.aggregatable` of [`GET /v1/basket-item-properties/fields`](/docs/entities/basket-item-properties/fields). Numeric functions accept fields of type `number`: `id`, `basketId`, `sort`.

## Request body fields

| Field | Type | Required | Description |
|---|---|---|---|
| `aggregate` | array | no | An array of expressions with `field` and `function`. Functions: `count`, `sum`, `avg`, `min`, `max`. For `count`, the field is `"*"`. When omitted, defaults to `[{ "field": "*", "function": "count" }]` |
| `filter` | object | no | Filter by fields from [`GET /v1/basket-item-properties/fields`](/docs/entities/basket-item-properties/fields).<br>[Filtering syntax](/docs/filtering). Example: `{ "basketId": 1001 }` |
| `groupBy` | string \| string[] | no | A grouping field or array of fields: `basketId`, `code` |
| `groupOrderBy` | array | no | Sort groups using objects with `field` and `direction`. Use `count`, a field from `groupBy`, or `<field>:<function>` from a numeric `aggregate` expression. Directions: `asc`, `desc`. Defaults to `desc`. Requires `groupBy` |
| `groupLimit` | number | no | Number of groups to return. Requires `groupBy` |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/basket-item-properties/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"aggregate":[{"field":"*","function":"count"}],"groupBy":"code","groupOrderBy":[{"field":"count","direction":"desc"}],"groupLimit":3}'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/basket-item-properties/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"aggregate":[{"field":"*","function":"count"}],"groupBy":"code","groupOrderBy":[{"field":"count","direction":"desc"}],"groupLimit":3}'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/basket-item-properties/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "aggregate": [
      {
        "field": "*",
        "function": "count"
      }
    ],
    "groupBy": "code",
    "groupOrderBy": [
      {
        "field": "count",
        "direction": "desc"
      }
    ],
    "groupLimit": 3
  }),
})

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

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/basket-item-properties/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "aggregate": [
      {
        "field": "*",
        "function": "count"
      }
    ],
    "groupBy": "code",
    "groupOrderBy": [
      {
        "field": "count",
        "direction": "desc"
      }
    ],
    "groupLimit": 3
  }),
})

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

To group by multiple fields, pass `groupBy` as an array.

## Other scenarios

The blocks below are request bodies.

Count properties of one basket item:

```json
{
  "filter": {
    "basketId": 1001
  },
  "aggregate": [
    {
      "field": "*",
      "function": "count"
    }
  ]
}
```

Sum the sort order and find the maximum property ID:

```json
{
  "aggregate": [
    {
      "field": "sort",
      "function": "sum"
    },
    {
      "field": "id",
      "function": "max"
    }
  ]
}
```

## Response fields

| Field | Type | Description |
|---|---|---|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Total number of properties matching the filter |
| `data.aggregates` | object | Numeric results by field and function. Empty for `count` alone |
| `data.aggregates.<field>.truncated` | boolean | Present as `true` when numeric results were calculated from an incomplete set of records |
| `data.groups` | array | Present with `groupBy`. Each group contains the grouping field value, `count`, and `aggregates` |
| `data.groups[].count` | number | Number of processed records in the group |
| `data.groups[].aggregates` | object | Numeric results within the group |
| `data.groups[].truncated` | boolean | Present as `true` for an incomplete set of records. The group's count and calculations cover the processed records |
| `data.meta.totalRecords` | number | Total number of records matching the filter |
| `data.meta.recordsProcessed` | number | Number of processed records, up to 5000. `0` without grouping or numeric functions |
| `data.meta.truncated` | boolean | `true` when fewer records were read than the reported total, including due to the 5000-record cap, or when reading stopped on a subpage error. `false` for a complete response. Always `false` without grouping or numeric functions |
| `data.meta.recordsShortfall` | number | Number of unread records: `totalRecords - recordsProcessed`. Present when records are missing, including at the 5000-record cap |
| `data.meta.pageErrorSample` | object | A sample subpage error. Present when reading stopped on an error |
| `data.meta.warnings` | array | Contains a warning with code `AGGREGATE_TRUNCATED` for an incomplete set of records |
| `data.meta.groupTotal` | number | Present with `groupBy`: the number of groups before `groupLimit` is applied |
| `data.meta.groupsTruncated` | boolean | Present with `groupBy`. `true` when `groupLimit` limits the returned groups |

## Response example

```json
{
  "success": true,
  "data": {
    "count": 249,
    "aggregates": {},
    "groups": [
      {
        "code": "CATALOG.XML_ID",
        "count": 69,
        "aggregates": {}
      },
      {
        "code": "PRODUCT.XML_ID",
        "count": 69,
        "aggregates": {}
      },
      {
        "code": "Color",
        "count": 39,
        "aggregates": {}
      }
    ],
    "meta": {
      "totalRecords": 249,
      "recordsProcessed": 249,
      "truncated": false,
      "groupTotal": 7,
      "groupsTruncated": true
    }
  }
}
```

Without `groupBy`, the response omits `data.groups`.

## Error response example

400 — the field `name` is not available for grouping:

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

## Errors

| HTTP | Code | Description |
|---|---|---|
| 400 | `INVALID_PARAMS` | Unknown aggregate function |
| 400 | `INVALID_PARAMS` | The `groupBy` field is neither `basketId` nor `code` |
| 400 | `INVALID_PARAMS` | A numeric function was requested for a string field such as `value` |
| 422 | `BITRIX_ERROR` | Bitrix24 rejected the request. The reason is in `error.message` |
| 503 | `BITRIX_TIMEOUT` | Bitrix24 did not respond in time |
| 502 | `BITRIX_UNAVAILABLE` | Bitrix24 could not be reached |
| 403 | `SCOPE_DENIED` | The API key lacks the `sale` scope |
| 401 | `MISSING_API_KEY` | The `X-Api-Key` header is missing |
| 401 | `TOKEN_MISSING` | No Bitrix24 access tokens are configured |
| 429 | `RATE_LIMITED` | The request rate limit was exceeded. Retry after the interval in the `Retry-After` header |

For the full list of common API errors, see [Error codes](/docs/errors).

## Known specifics

**Counting and calculations.** A lone `count` without `groupBy` does not download records. Numeric functions and grouping require reading records.

## See also

- [List basket item properties](/docs/entities/basket-item-properties/list)
- [Search basket item properties](/docs/entities/basket-item-properties/search)
- [Basket item property fields](/docs/entities/basket-item-properties/fields)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
