@todo fix me!
v1.0.1
  • Get Started
  • Templates
  • GitHub
  • Overview
  • B24Hook
  • Methods
  • callMethod
  • callFastListMethod
  • fetchListMethod
  • callBatch
  • callBatchByChunk
  • getTargetOrigin
  • getTargetOriginWithPath
  • getLogger
  • setLogger
  • destroy
  • getHttpClient
  • offClientSideWarning
  • Getters
  • auth
  • isInit
  • b24ui
  • b24icons
v1.0.1
  • Docs
  • Frame
  • Hook
  • OAuth
  • Templates

B24Hook.callFastListMethod

Use B24Hook.callFastListMethod() to quickly fetch all list items from the Bitrix24 REST API. The method automatically performs all necessary requests to retrieve the complete dataset using an optimized approach that does not count the total number of items, significantly speeding up the process when working with large data volumes. Works only in server environment.
B24Hook
TypeB24
The B24Hook object is intended exclusively for use on the server.
  • A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, mobile app).
  • For the client side, use B24Frame.
The B24Hook.callListMethod() method is deprecated. Use the B24Hook.callFastListMethod() method instead.

Quick Overview

Use callFastListMethod to quickly fetch all data from methods that return lists. The method uses an optimized approach without counting the total number of items, which significantly speeds up request execution when working with large data volumes.

The method returns a Promise that resolves to a Result object containing the complete array of retrieved data.

// Basic usage
import { B24Hook } from '@bitrix24/b24jssdk'

const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

const response = await $b24.callFastListMethod('crm.item.list', {
  entityTypeId: 2, // Entity type ID (e.g., 2 for Company)
  select: ['id', 'title']
}, 'id', 'items')

Method Signature

callFastListMethod<T = unknown>(
  method: string,
  params?: {
    order?: any
    filter?: any
    [key: string]: any
  },
  idKey?: string,
  customKeyForResult?: string | null
): Promise<Result<T[]>>

Parameters

ParameterTypeRequiredDescription
methodstringYesThe name of the REST API method to call (e.g., crm.item.list).
paramsobjectNoAn object with parameters to pass to the API method. Can contain order, filter, and other valid parameters. Important: Do not pass the start parameter — the method manages it automatically.
idKeystringNoID field name. Specifies the field used for filtering during optimized pagination. Default is 'ID'. Use 'id' (lowercase) if the API method returns IDs in that format.
customKeyForResultstringNoCustom key for data extraction. If the API method returns the result not in the main result field but in a nested one (e.g., result.tasks), specify the key here (e.g., 'tasks'). Default is null (data is taken from the root of result).

Return Value

Promise<Result<T[]>> — a promise that resolves to a Result object containing the complete array of items of type T. This object provides:

  • .getData(): T[] — returns the complete array of all retrieved data.
  • .isSuccess: boolean — a flag indicating the successful execution of all requests.
  • .getErrorMessages(): string[] — an array of error messages.

Key Concepts

Optimized pagination without counting

callFastListMethod uses a special optimization for quickly retrieving large data volumes:

  1. Disabling total count: Uses the start: -1 parameter, which disables the calculation of the total number of items, significantly speeding up request execution.
  2. Filtering by ID: After receiving each page of data, the method updates the filter, adding a condition '>ID': lastId to get the next batch of data.
  3. Automatic completion: The process continues until an empty response is received.

Important Limitations

  • Mandatory sorting by ID: The method requires that the sorting order by the ID field be specified in the parameters (e.g., order: { id: 'asc' }). This is necessary for the filtering to work correctly.

Error Handling

Always check the result using isSuccess and handle errors.

const response = await $b24.callFastListMethod('some.method', {}, 'id', 'items')

if (!response.isSuccess) {
  // Handling API error
  console.error(new Error(`API Error: ${response.getErrorMessages().join('; ')}`))
  return
}

// Working with a successful result
const data = response.getData()

Examples

Getting all companies with filtering

AllCrmItems.ts
import { B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk'

type Company = {
  id: number
  title: string
}

const devMode = typeof import.meta !== 'undefined' && (globalThis._importMeta_.env?.DEV || false)
const $logger = LoggerFactory.createForBrowser('Example:AllCrmItems', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

try {
  const response = await $b24.callFastListMethod<Company>(
    'crm.item.list',
    {
      entityTypeId: EnumCrmEntityTypeId.company,
      filter: {
        // use some filter by title
        '=%title': 'Prime%'
      },
      select: ['id', 'title']
    },
    'id', // ID field in the response
    'items' // The key under which the data is located (for methods like crm.item.list)
  )

  if (!response.isSuccess) {
    throw new Error(`API Error: ${response.getErrorMessages().join('; ')}`)
  }

  const list = response.getData()
  $logger.info(`Companies list (${list?.length})`, { list })
} catch (error) {
  $logger.error('some error', { error })
}

Retrieving all deals with a specific stage and stage change date

AllDealsByStage.ts
import type { ISODate } from '@bitrix24/b24jssdk'
import { B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk'

type Deal = {
  id: number
  title: string
  opportunity: number
  stageId: string
  movedTime: ISODate
}

const devMode = typeof import.meta !== 'undefined' && (globalThis._importMeta_.env?.DEV || false)
const $logger = LoggerFactory.createForBrowser('Example:AllDealsByStage', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

try {
  const sixMonthAgo = new Date()
  sixMonthAgo.setMonth((new Date()).getMonth() - 6)
  sixMonthAgo.setHours(0, 0, 0)
  const response = await $b24.callFastListMethod<Deal>(
    'crm.item.list',
    {
      entityTypeId: EnumCrmEntityTypeId.deal,
      filter: {
        '>=movedTime': sixMonthAgo, // Stage changed at least 6 months ago
        '=stageId': 'WON' // Only winning deals
      },
      select: ['id', 'title', 'opportunity', 'stageId', 'movedTime']
    },
    'id',
    'items'
  )

  if (!response.isSuccess) {
    throw new Error(`API Error: ${response.getErrorMessages().join('; ')}`)
  }

  const wonDeals = response.getData()
  const totalRevenue = (wonDeals || []).reduce((sum, deal) => sum + (deal.opportunity || 0), 0)

  $logger.info('response', {
    wonDeals: wonDeals?.length,
    totalAmount: totalRevenue
  })
} catch (error) {
  $logger.error('some error', { error })
}

Getting all tasks and grouping them by responsible person

AllTasks.ts
import type { NumberString } from '@bitrix24/b24jssdk'
import { B24Hook, LoggerFactory } from '@bitrix24/b24jssdk'

type Task = {
  id: NumberString
  title: string
  responsibleId: NumberString
}

const devMode = typeof import.meta !== 'undefined' && (globalThis._importMeta_.env?.DEV || false)
const $logger = LoggerFactory.createForBrowser('Example:AllTasks', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

try {
  const response = await $b24.callFastListMethod<Task>(
    'tasks.task.list',
    {
      filter: { REAL_STATUS: [2, 3] }, // Tasks in progress and pending execution
      select: ['ID', 'TITLE', 'RESPONSIBLE_ID']
    },
    'id',
    'tasks' // The key under which the tasks are located in the response
  )

  if (!response.isSuccess) {
    throw new Error(`API Error: ${response.getErrorMessages().join('; ')}`)
  }

  const activeTasks = response.getData()
  $logger.debug(`Active tasks: ${activeTasks?.length}`)

  // Group by responsible
  const tasksByResponsible = (activeTasks || []).reduce((acc: Record<number, Task[]>, task) => {
    const responsibleId = Number.parseInt(task.responsibleId)
    if (!acc[responsibleId]) {
      acc[responsibleId] = []
    }

    acc[responsibleId].push(task)
    return acc
  }, {})

  $logger.info('Tasks by Responsible Person', { tasksByResponsible })
} catch (error) {
  $logger.error('some error', { error })
}

Alternatives and Recommendations

  • For step-by-step streaming processing of very large lists: Use fetchListMethod. Returns an async generator that yields data page by page, allowing processing to start before the entire list is loaded and saving memory.
  • For batch operations: Use callBatch to execute up to 50 commands in a single request.
  • For working with the legacy callListMethod: Migrate to callFastListMethod, as it is more optimized and the recommended replacement.
  • When you need the total item count: Use the regular callMethod with manual pagination, as callFastListMethod does not count the total.
  • On the client (browser): Use the built-in B24Frame object instead of B24Hook.

References

  • Result — Documentation for the result object.
  • Official Bitrix24 REST API Documentation — Reference for all available methods.
  • Working with Large Volumes of Data — Recommendations for optimizing code to retrieve large data.

callMethod

The primary method for executing Bitrix24 REST API calls via webhook. Allows calling any REST API method with specified parameters. Works only in a server environment. Works only in server environment.

fetchListMethod

Use `B24Hook.fetchListMethod()` for step-by-step stream processing of very large data lists. It returns an asynchronous generator that fetches data page by page, allowing processing to begin before the entire list has finished loading and conserving memory. It doesn

On this page

  • Quick Overview
  • Method Signature
    • Parameters
    • Return Value
  • Key Concepts
    • Important Limitations
    • Error Handling
  • Examples
    • Getting all companies with filtering
    • Retrieving all deals with a specific stage and stage change date
    • Getting all tasks and grouping them by responsible person
  • Alternatives and Recommendations
  • References
Releases
Published under MIT License.

Copyright © 2024-present Bitrix24