### Install fast-bitrix24 via PIP Source: https://pypi.org/project/fast-bitrix24/index This command installs the fast-bitrix24 library using pip, the Python package installer. Ensure you have Python and pip installed on your system. ```bash pip install fast-bitrix24 ``` -------------------------------- ### Install fast-bitrix24 using pip Source: https://pypi.org/project/fast-bitrix24/1 Installs the fast-bitrix24 library version 1.5.4 using pip. It's recommended to use a virtual environment for managing project dependencies. ```bash pip install fast-bitrix24==1.5.4 ``` -------------------------------- ### Install fast-bitrix24 using pip Source: https://pypi.org/project/fast-bitrix24/0 This command installs the fast-bitrix24 library version 0.5.3 using pip. It's a prerequisite for using the library in your Python projects. ```bash pip install fast_bitrix24==0.5.3 ``` -------------------------------- ### GET /api/get_all Source: https://pypi.org/project/fast-bitrix24/1 Fetches a complete list of entities for a given API method. Handles pagination automatically. ```APIDOC ## GET /api/get_all ### Description Retrieves a full list of entities based on the provided method and parameters. This method automatically handles paginated responses from the server to return a complete list. ### Method GET ### Endpoint /api/get_all ### Parameters #### Query Parameters - **method** (string) - Required - The REST API method to query. - **params** (dict) - Optional - Parameters to pass to the method. Must be in the format specified by the Bitrix24 REST API documentation. The `start`, `limit`, and `order` parameters are not supported by this method. ### Request Example ```json { "method": "crm.deal.list", "params": { "filter": { "CLOSED": "N" } } } ``` ### Response #### Success Response (200) - **list | dict** - A list or dictionary containing the requested entities. #### Response Example ```json [ { "id": "1", "name": "Deal 1" }, { "id": "2", "name": "Deal 2" } ] ``` ``` -------------------------------- ### Configure fast_bitrix24 Client for Rate Limiting Source: https://pypi.org/project/fast-bitrix24/index This example shows how to initialize the `Bitrix` client with custom parameters to control the request rate and load on the Bitrix24 server. Parameters like `request_pool_size`, `requests_per_second`, `batch_size`, and `operating_time_limit` can be adjusted to fine-tune the library's behavior and prevent server errors. ```python bx = Bitrix( webhook, request_pool_size = 20, # default is 50 requests_per_second = 1.0, # default is 2.0 batch_size = 20, # default is 50 operating_time_limit = 100, # default is 480 ) ``` -------------------------------- ### GET /api/list_and_get Source: https://pypi.org/project/fast-bitrix24/1 Downloads all entity IDs using a method branch's `.list` method, then fetches all fields for each entity using the `.get` method. ```APIDOC ## GET /api/list_and_get ### Description Downloads a list of all entity IDs using the `method_branch + '.list'` method, and then retrieves the values of all fields for all elements using the `method_branch + '.get'` method. This approach is significantly faster for large datasets compared to `get_all()` with a broad select parameter. ### Method GET ### Endpoint /api/list_and_get ### Parameters #### Query Parameters - **method_branch** (string) - Required - The group of methods to use (e.g., 'crm.lead', 'tasks.task'). This group must have `*.list` and `*.get` sub-methods. - **ID_field_name** (string) - Optional - The name of the field that the `*.get` method uses to accept element identifiers. Defaults to 'ID'. ### Request Example ```json { "method_branch": "crm.lead" } ``` ### Response #### Success Response (200) - **dict** - A dictionary containing the complete content of all elements, formatted similarly to the output of `get_by_ID()`. #### Response Example ```json { "1": { "fields": { "name": "Lead 1" } }, "2": { "fields": { "name": "Lead 2" } } } ``` #### Limitations This method may not work with method groups where the identifier field name differs between the `*.list` and `*.get` methods (e.g., `tasks.task.list` returns ID in 'ID', but `tasks.task.get` expects it in 'taskId'). ``` -------------------------------- ### Python: Get All Entities with get_all() Method Source: https://pypi.org/project/fast-bitrix24/0 The `get_all()` method simplifies retrieving all records for a given API method. It automatically handles pagination, making multiple requests as needed to fetch the complete dataset. Note that 'start', 'limit', and 'order' parameters are not supported when using `get_all()`. ```python all_deals = b.get_all('crm.deal.list', params={'filter': {'STATUS_ID': '1'}}) ``` -------------------------------- ### Get All Entities Source: https://pypi.org/project/fast-bitrix24/0 Retrieves a complete list of entities by handling pagination automatically. ```APIDOC ## GET /get_all ### Description Fetches all entities for a given API method, automatically handling server-side pagination. ### Method GET (internally handled by the library) ### Endpoint N/A (Internal library method) ### Parameters #### `get_all(self, method: str, params: dict = None)` - **method** (str) - Required - The Bitrix24 REST API method to query (e.g., 'crm.deal.list'). - **params** (dict) - Optional - Parameters for the API method, in the format specified by Bitrix24 REST API documentation. `start`, `limit`, and `order` parameters are not supported directly as `get_all` manages them. ### Request Example ```python # Assuming 'b' is an instance of Bitrix or BitrixAsync all_deals = b.get_all('crm.deal.list', {'filter': {'STATUS_ID': '1'}}) ``` ### Response #### Success Response - Returns a list containing all entities matching the specified method and parameters. The list is flattened, and the order of elements corresponds to the order of requests. #### Response Example ```json [ { "ID": "1", "TITLE": "Deal 1", ... }, { "ID": "2", "TITLE": "Deal 2", ... } ] ``` **Note:** For very long lists, a standard Python `warning` may be issued if new elements are added to the list while `get_all` is processing, potentially causing the total count to differ from the initial `total` value. ``` -------------------------------- ### Python: Make Asynchronous API Calls with BitrixAsync Source: https://pypi.org/project/fast-bitrix24/0 Methods on the `BitrixAsync` client mirror their synchronous counterparts but are designed to be `await`ed. This enables non-blocking execution, preventing your application from freezing while waiting for API responses. For example, `b.get_all('crm.lead.list')` fetches all leads asynchronously. ```python leads = await b.get_all('crm.lead.list') ``` -------------------------------- ### Get all entities using get_all() in Python Source: https://pypi.org/project/fast-bitrix24/0 Shows how to retrieve a complete list of entities using the `get_all()` method. It can fetch all users or specific entities like deals with custom parameters. ```python # get list of users users = b.get_all('user.get') # get list of deals in progress, including custom fields deals = b.get_all('crm.deal.list', params={ 'select': ['*', 'UF_*'], 'filter': {'CLOSED': 'N'} }) ``` -------------------------------- ### Fetch All Entities with get_all in Python Source: https://pypi.org/project/fast-bitrix24/1 Retrieves a complete list of entities from the Bitrix24 REST API by handling paginated responses automatically. It accepts the API method and optional parameters, excluding 'start', 'limit', and 'order'. ```python def get_all(self, method: str, params: dict = None) -> list | dict: """Получить полный список сущностей по запросу `method`. `get_all()` самостоятельно обрабатывает постраничные ответы сервера, чтобы вернуть полный список (подробнее см. "Как это работает" выше). #### Параметры * `method: str` - метод REST API для запроса к серверу. * `params: dict` - параметры для передачи методу. Используется именно тот формат, который указан в документации к REST API Битрикс24. `get_all()` не поддерживает параметры `start`, `limit` и `order`. Возвращает полный список сущностей, имеющихся на сервере, согласно заданным методу и параметрам. """ pass ``` -------------------------------- ### Sort Results from get_all() in fast_bitrix24 Source: https://pypi.org/project/fast-bitrix24/index This example demonstrates how to sort the results obtained from the `get_all()` method in `fast_bitrix24`. Since `get_all()` returns results in the order they are received from the server, this snippet shows how to manually sort a list of deals by their 'ID' using a lambda function. ```python deals = bx.get_all('crm.deal.list') deals.sort(key = lambda d: int(d['ID'])) ``` -------------------------------- ### Bitrix Client Initialization Source: https://pypi.org/project/fast-bitrix24/0 Details on how to initialize the synchronous Bitrix client. ```APIDOC ## POST /__init__ (Bitrix Client) ### Description Initializes an instance of the synchronous `Bitrix` client for interacting with the Bitrix24 API. ### Method Constructor ### Endpoint N/A (Client-side instantiation) ### Parameters #### `__init__(self, webhook: str, verbose: bool = True)` - **webhook** (str) - Required - The webhook URL obtained from Bitrix24. - **verbose** (bool) - Optional, defaults to `True` - If `True`, displays a progress bar during request execution. ### Request Example ```python from fast_bitrix24 import Bitrix webhook_url = "YOUR_WEBHOOK_URL" b = Bitrix(webhook_url, verbose=True) ``` ### Response #### Success Response - Returns an initialized `Bitrix` client object. #### Response Example (No direct response, object is created) **Note:** It is recommended to use a single `Bitrix` instance per application account and IP address to properly manage request speed limits. ``` -------------------------------- ### Bitrix Class Initialization Source: https://pypi.org/project/fast-bitrix24/1 Initialize the `Bitrix` client with optional parameters to control verbosity and velocity policy adherence. ```APIDOC ## Bitrix Client Initialization ### Description Initializes the main `Bitrix` client object, which manages API requests and rate limiting. ### Method `__init__` ### Parameters - **webhook** (str) - Required - The Bitrix24 webhook URL. - **verbose** (bool) - Optional - If True, displays a progress bar during operations. Defaults to True. - **respect_velocity_policy** (bool) - Optional - If True, adheres strictly to Bitrix24's official rate limits. Defaults to False (enabling adaptive throttling). - **client** (aiohttp.ClientSession) - Optional - An existing `aiohttp.ClientSession` object to use for HTTP requests. ### Example ```python from fast_bitrix24 import Bitrix webhook_url = "YOUR_WEBHOOK_URL" # Default initialization (verbose, adaptive throttling) bitrix_client = Bitrix(webhook_url) # Initialization respecting official velocity policy bitrix_client_strict = Bitrix(webhook_url, respect_velocity_policy=True) # Initialization without progress bar bitrix_client_quiet = Bitrix(webhook_url, verbose=False) ``` ``` -------------------------------- ### Initialize Bitrix client with webhook in Python Source: https://pypi.org/project/fast-bitrix24/0 Demonstrates how to initialize the Bitrix client using a webhook URL. Replace the placeholder URL with your actual Bitrix24 webhook for authentication and access. ```python from fast_bitrix24 import * # replace with your webhook for Bitrix24 access webhook = "https://your_domain.bitrix24.ru/rest/1/your_code/" b = Bitrix(webhook) ``` -------------------------------- ### Initialize Bitrix24 Client in Python Source: https://pypi.org/project/fast-bitrix24/1 Initializes the synchronous Bitrix24 client using a provided webhook URL. Ensure the webhook URL is correct and has the necessary permissions. ```python from fast_bitrix24 import Bitrix # replace with your webhook for Bitrix24 access webhook = "https://your_domain.bitrix24.ru/rest/1/your_code/" b = Bitrix(webhook) ``` -------------------------------- ### GET /api/get_by_ID Source: https://pypi.org/project/fast-bitrix24/1 Fetches a list of entities by their IDs for a given API method. Useful for retrieving specific entities when a single call is not possible or efficient. ```APIDOC ## GET /api/get_by_ID ### Description Retrieves a list of entities based on the provided method and a list of IDs. This is useful when you need a specific set of entities rather than all available entities, or when the REST API does not support fetching entities in a single call. ### Method GET ### Endpoint /api/get_by_ID ### Parameters #### Query Parameters - **method** (string) - Required - The REST API method to query. - **ID_list** (Iterable) - Required - A list of IDs for which entities will be requested. - **ID_field_name** (string) - Optional - The name of the field where the IDs from `ID_list` will be substituted. Defaults to 'ID'. - **params** (dict) - Optional - Parameters to pass to the method. Must be in the format specified by the Bitrix24 REST API documentation. If an 'ID' parameter is included in `params`, a `ValueError` will be raised. ### Request Example ```json { "method": "crm.deal.contact.item.get", "ID_list": ["1", "2", "3"], "ID_field_name": "deal_id" } ``` ### Response #### Success Response (200) - **dict** - A dictionary where keys are the IDs from `ID_list` and values are the results of the query for each ID. #### Response Example ```json { "1": [ { "contact_id": "101" } ], "2": [ { "contact_id": "102" } ], "3": [] } ``` ``` -------------------------------- ### Batch API Call Source: https://pypi.org/project/fast-bitrix24/0 Demonstrates how to make a batch call to the Bitrix24 API to execute multiple commands simultaneously. ```APIDOC ## POST /call_batch ### Description Executes multiple Bitrix24 API commands in a single batch request. ### Method POST ### Endpoint `/call_batch` ### Parameters #### Request Body - **halt** (integer) - Required - If 0, continues processing commands even if one fails. If 1, stops processing on the first error. - **cmd** (object) - Required - An object where keys are command aliases and values are the Bitrix24 API methods to call. You can reference results from previous commands using `$result[alias][index][field]`. ### Request Example ```json { "halt": 0, "cmd": { "deals": "crm.deal.list", "activities": "crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]" } } ``` ### Response #### Success Response (200) - **result** (object) - An object containing the results of each command, keyed by their aliases. #### Response Example ```json { "result": { "deals": [ { "ID": "1", "TITLE": "Deal 1", ... } ], "activities": [ { "ID": "10", "SUBJECT": "Activity 1", ... } ] }, "time": { "start": 1678886400, "finish": 1678886401, "duration": 1, "processing": 0.5, "date_create": "2023-03-15T12:00:00+00:00" } } ``` ``` -------------------------------- ### Get entities by ID using get_by_ID() in Python Source: https://pypi.org/project/fast-bitrix24/0 Illustrates fetching properties of entities based on their IDs using the `get_by_ID()` method. This is useful for retrieving related entities, such as contacts associated with deals. ```python ''' get all contacts associated with deals in the format [ (deal_ID1, [contact1, contact2, ...]), (deal_ID2, [contact1, contact2, ...]), ... ] ''' contacts = b.get_by_ID('crm.deal.contact.items.get', [d['ID'] for d in deals]) ``` -------------------------------- ### Use BitrixAsync for Asynchronous Environments Source: https://pypi.org/project/fast-bitrix24/index This snippet illustrates the recommended way to use `fast_bitrix24` in asynchronous environments like Jupyter notebooks or Spyder. It replaces the synchronous `Bitrix` client with `BitrixAsync` and uses `await` before calling asynchronous methods like `get_all()` to properly handle the asyncio event loop. ```python from fast_bitrix24 import BitrixAsync bx = BitrixAsync(webhook) leads = await bx.get_all('crm.lead.list') ``` -------------------------------- ### Get Entities by IDs Source: https://pypi.org/project/fast-bitrix24/0 Retrieves a list of entities based on a specified REST API method and a list of IDs. This is useful when you need specific entities by their IDs or when the REST API doesn't offer a direct way to fetch them in a single call. ```APIDOC ## GET /api/entities/by_id ### Description Retrieves a list of entities using a specified REST API method and a list of IDs. ### Method POST ### Endpoint /api/entities/by_id ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (str) - Required - The REST API method to query. - **ID_list** (Sequence) - Required - A list of IDs for which to retrieve entities. - **ID_field_name** (str) - Optional - The name of the field to use for the IDs. Defaults to 'ID'. - **params** (dict) - Optional - Parameters to pass to the method. Cannot contain an 'ID' parameter. ### Request Example ```json { "method": "crm.deal.contact.item.get", "ID_list": ["1", "2", "3"], "ID_field_name": "deal_id", "params": {"some_other_param": "value"} } ``` ### Response #### Success Response (200) - **result** (list) - A list of tuples, where each tuple contains the ID and the result of the query for that ID. The list length will match the input `ID_list` length. #### Response Example ```json { "result": [ ["1", [{"contact_id": "10"}]], ["2", []], ["3", [{"contact_id": "12"}, {"contact_id": "13"}]] ] } ``` ``` -------------------------------- ### Initialize synchronous Bitrix client Source: https://pypi.org/project/fast-bitrix24/index This Python code snippet demonstrates how to initialize the synchronous Bitrix client. It requires the Bitrix24 webhook URL for authentication and access. ```python from fast_bitrix24 import Bitrix # replace with your webhook for Bitrix24 access webhook = "https://your_domain.bitrix24.ru/rest/1/your_code/" bx = Bitrix(webhook) ``` -------------------------------- ### Python: Initialize Bitrix24 Asynchronous Client Source: https://pypi.org/project/fast-bitrix24/0 To use the fast-bitrix24 library in an asynchronous environment, instantiate the `BitrixAsync` client instead of the regular `Bitrix` client. This client allows you to make non-blocking API calls, suitable for applications using asyncio. ```python from fast_bitrix24 import BitrixAsync b = BitrixAsync(webhook) ``` -------------------------------- ### Customized Lead Fetch with Parameters in Python Source: https://pypi.org/project/fast-bitrix24/1 Fetches deals with specific fields ('*','UF_*') and filters for open deals ('CLOSED': 'N') using the `get_all` method with custom parameters. ```python # list of deals in progress, including custom fields deals = b.get_all( 'crm.deal.list', params={ 'select': ['*', 'UF_*'], 'filter': {'CLOSED': 'N'} }) ``` -------------------------------- ### Call Batch Method with $result Keyword (Python) Source: https://pypi.org/project/fast-bitrix24/1 Demonstrates how to use the `call_batch` method to execute multiple Bitrix24 API commands sequentially. It shows how to reference the result of a previous command in a subsequent one using the `$result` keyword. This is useful for complex operations requiring chained API calls. ```python results = b.call_batch({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', # берем список сделок # и берем список дел по первой из них 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### Bitrix Class Initialization Source: https://pypi.org/project/fast-bitrix24/1 The `Bitrix` class is used to send all requests to the Bitrix24 server. It manages request rate limiting and error handling. Key initialization parameters include the webhook URL, verbosity for progress bars, and an option to respect Bitrix24's velocity policy. ```python __init__(self, webhook: str, verbose: bool = True, respect_velocity_policy: bool = False, client: aiohttp.ClientSession = None): ``` -------------------------------- ### Make Single and List Calls with call() Method (Python) Source: https://pypi.org/project/fast-bitrix24/1 Explains that the `call()` method can handle both single API requests and requests for a list of items. It demonstrates how to pass a single method and parameters for an individual request, and advises that for multiple similar calls, it's more efficient to form a list and call `call()` once. ```python method = 'crm.lead.add' params = {'fields': {'TITLE': 'Чпок'}} b.call(method, params) ``` -------------------------------- ### Asynchronous Operations Source: https://pypi.org/project/fast-bitrix24/1 For asynchronous programming, use the `BitrixAsync` class and its corresponding methods, such as `await b.get_all(...)`. ```APIDOC ## Asynchronous API Calls ### Description Provides an asynchronous interface for interacting with the Bitrix24 API using `BitrixAsync`. Methods mirror the synchronous `Bitrix` class but are awaitable. ### Method Various (e.g., GET, POST, depending on the underlying method) ### Endpoint N/A (Managed internally by the library) ### Usage ```python from fast_bitrix24 import BitrixAsync webhook = "YOUR_WEBHOOK_URL" b = BitrixAsync(webhook) # Example of an asynchronous call async def fetch_leads(): leads = await b.get_all('crm.lead.list') print(f"Fetched {len(leads)} leads.") # To run this, you would typically use an asyncio event loop: # import asyncio # asyncio.run(fetch_leads()) ``` ### Response #### Success Response (200) - **result** (list or dict) - The result of the asynchronous API call. ``` -------------------------------- ### Enable Logging for fast_bitrix24 Requests Source: https://pypi.org/project/fast-bitrix24/index This snippet demonstrates how to enable logging for the fast_bitrix24 library to monitor server requests and responses. It adds a stream handler to the library's logger, allowing output to the console. This is useful for debugging and understanding the data being sent and received. ```python import logging logging.getLogger('fast_bitrix24').addHandler(logging.StreamHandler()) ``` -------------------------------- ### General API Call with call in Python Source: https://pypi.org/project/fast-bitrix24/1 A versatile method for invoking any Bitrix24 REST API endpoint when `get_all` or `get_by_ID` are not suitable. It supports single calls with dictionary parameters or batch calls with iterable parameters. The `raw` option prevents batching for specific use cases. ```python def call(self, method: str, items: dict | Iterable[dict] | Any = None, /, raw: bool = False) -> dict | list[dict] | Any: """Вызвать метод REST API. Самый универсальный метод, применяемый, когда `get_all` и `get_by_ID` не подходят. #### Параметры * `method: str` - метод REST API * `items: dict | Iterable[dict]` - параметры вызываемого метода. Может быть списком, и тогда метод будет вызван для каждого элемента списка, а может быть одним словарем параметров для единичного вызова. * `raw: bool = False` - если `True`, то `items` воспринимается как один элемент (даже если в `items` был передан список) и не заворачивается в батч. Требуется для работы со старыми методами, принимающими на вход параметры списком (`tasks.elapseditem.*`), а также для передачи значений `None` (которые плохо обрабатываются в батче). Подробней см. PR #158. По умолчанию - `False`. Если `raw=False`, то `call()` вызывает `method`, последовательно подставляя в параметры запроса все элементы `items`, и возвращает список ответов сервера для каждого из отправленных запросов. При этом запросы к Битриксу группируются в батчи. Либо, если `items` - не список, а словарь с параметрами, то происходит единичный вызов и возвращается его результат. """ pass ``` -------------------------------- ### General API Call Source: https://pypi.org/project/fast-bitrix24/1 The `call(raw=True)` method is recommended for specific use cases, such as calling methods that return dictionaries or when parameters need to be explicitly set to None. ```APIDOC ## POST /api/call ### Description Allows direct calls to Bitrix24 API methods. Particularly useful for methods like `crm.lead.fields` or `crm.deal.fields` that return dictionaries, or for explicitly setting parameter values to `None` to clear them. ### Method POST ### Endpoint /api/call ### Parameters #### Query Parameters - **raw** (bool) - Optional - If True, returns the raw dictionary response. #### Request Body - **method** (str) - Required - The Bitrix24 API method to call (e.g., `crm.lead.fields`). - **params** (dict) - Optional - Parameters for the API method. Can include `None` values to clear fields. ### Request Example ```json { "method": "crm.lead.fields", "params": {}, "raw": true } ``` ```json { "method": "crm.lead.update", "params": { "ID": 123, "fields": { "DESCRIPTION": null } }, "raw": true } ``` ### Response #### Success Response (200) - **result** (dict or list) - The result of the API call. The structure depends on the method called and the `raw` parameter. ``` -------------------------------- ### Download All Data with list_and_get in Python Source: https://pypi.org/project/fast-bitrix24/1 Efficiently downloads all entity data by first fetching a list of IDs using a '.list' method and then retrieving full details for each ID using a '.get' method. This approach is significantly faster for large datasets compared to `get_all()`. ```python def list_and_get(self, method_branch: str, ID_field_name='ID') -> dict: """Скачать список всех ID при помощи метода `method_branch + '.list'`, а затем значения всех полей всех элементов при помощи метода `method_branch + '.get'`. `method_branch` - группа методов, в которой есть подметоды `*.list` и `*.get`, например `crm.lead` или `tasks.task`. Например: ``` all_lead_info = b.list_and_get('crm.lead') ``` Подобный подход показывает на порядок большую скорость получения больших объемов данных (полный набор полей на списках более 20 тыс. элементов), чем `get_all()` с параметром `'select': ['*', 'UF_*']`. См. сравнение скоростей разных стратегий получения данных. #### Параметры * `method_branch: str` - группа методов к использованию, например, "crm.lead". * `ID_field_name='ID'` - имя поля, в котором метод *.get принимает идентификаторы элементов (например, `'ID'` для метода `crm.lead.get`) Возвращает полное содержимое всех элементов в виде, используемом функцией `get_by_ID()` - словарь следующего вида: ``` { ID_1: <словарь полей сущности с ID_1>, ID_2: <словарь полей сущности с ID_2>, ... } ``` #### Ограничения `list_and_get()` не работает с теми группами методов, которые не поддерживают единое название поля с идентификатором в параметрах и результатах методов `*.list` и `*.get`. Например, `tasks.task.list` в результатах идентификатор задачи возвращает в поле `ID`, но `tasks.task.get` принимает идентификаторы задач в поле `taskId`. """ pass ``` -------------------------------- ### Python: Initialize Bitrix24 Synchronous Client Source: https://pypi.org/project/fast-bitrix24/0 The `Bitrix` client is used for synchronous interactions with the Bitrix24 API. It manages request rate limiting and performs validation on common parameters before sending requests to the server. Initialize it with your webhook URL. ```python from fast_bitrix24 import Bitrix b = Bitrix(webhook) ``` -------------------------------- ### Asynchronous API Calls Source: https://pypi.org/project/fast-bitrix24/0 Shows how to use the asynchronous client for non-blocking API interactions. ```APIDOC ## Asynchronous API Client ### Description Utilize the `BitrixAsync` client for asynchronous operations within your Python application. ### Method Instantiation and `await` calls ### Endpoint N/A (Client-side implementation) ### Parameters #### Constructor (`BitrixAsync`) - **webhook** (str) - Required - The Bitrix24 webhook URL. #### Methods (e.g., `get_all`) - **method** (str) - Required - The REST API method to call. - **params** (dict) - Optional - Parameters for the API method. ### Request Example ```python from fast_bitrix24 import BitrixAsync webhook_url = "YOUR_WEBHOOK_URL" b = BitrixAsync(webhook_url) # Example of an asynchronous call async def fetch_leads(): leads = await b.get_all('crm.lead.list') print(leads) ``` ### Response #### Success Response - The method returns data as specified by the called Bitrix24 API endpoint. For `get_all`, it returns a flattened list of all entities. #### Response Example (for `get_all`) ```json [ { "ID": "1", "TITLE": "Lead 1", ... }, { "ID": "2", "TITLE": "Lead 2", ... } ] ``` **Note:** Avoid using `slow()` context manager with `BitrixAsync` as it can lead to unpredictable behavior due to shared global state. ``` -------------------------------- ### call() with single request Source: https://pypi.org/project/fast-bitrix24/1 Demonstrates how to use the `call()` method for a single API request instead of a list, suitable for one-off operations. ```APIDOC ## POST /call ### Description Executes a single Bitrix24 API method call. ### Method POST ### Endpoint /call ### Parameters #### Request Body - **method** (string) - Required - The name of the Bitrix24 API method to call. - **params** (object) - Required - The parameters for the API method. ### Request Example ```python method = 'crm.lead.add' params = {'fields': {'TITLE': 'Example Lead'}} b.call(method, params) ``` ### Response #### Success Response (200) - **result** (object) - The result of the API method call. - **error** (object) - Information about any errors that occurred. #### Response Example ```json { "result": { "ID": "123" }, "error": null } ``` ``` -------------------------------- ### POST /api/call Source: https://pypi.org/project/fast-bitrix24/1 A universal method to call any REST API method. Suitable for scenarios where `get_all` and `get_by_ID` are not applicable. Supports batching and raw calls. ```APIDOC ## POST /api/call ### Description Executes a specified REST API method. This is the most versatile method, used when `get_all` and `get_by_ID` are not suitable. It supports calling methods with a single set of parameters, a list of parameter sets for batch processing, and a `raw` option for specific use cases. ### Method POST ### Endpoint /api/call ### Parameters #### Request Body - **method** (string) - Required - The REST API method to call. - **items** (dict | Iterable[dict] | Any) - Optional - The parameters for the method being called. Can be a dictionary for a single call or an iterable of dictionaries for multiple calls. If `raw` is True, this is treated as a single element even if it's a list. - **raw** (boolean) - Optional - If True, `items` is treated as a single element and not wrapped in a batch. Required for older methods that accept parameters as a list or when passing `None` values. Defaults to False. ### Request Example ```json { "method": "crm.deal.add", "items": { "fields": { "TITLE": "New Deal", "CONTACT_ID": 1, "BEGINDATE": "2023-01-01" } } } ``` ### Response #### Success Response (200) - **dict | list[dict] | Any** - The result of the API call. If `raw` is False and `items` is a list, this will be a list of responses for each item. If `items` is a dictionary, this will be the single response. If `raw` is True, the response format depends on the specific API method called. #### Response Example (for single call) ```json { "result": { "ID": "123" } } ``` #### Response Example (for batched call) ```json [ { "result": {"ID": "123"} }, { "result": {"ID": "124"} } ] ``` ``` -------------------------------- ### Execute Batch Calls with Bitrix24 REST API (Python) Source: https://pypi.org/project/fast-bitrix24/0 Executes a batch method call to the Bitrix24 REST API, supporting the use of results from one command in another via the '$result' keyword. It returns a dictionary where keys are command names and values are their execution results. This is efficient for making multiple related API calls in a single request. ```Python results = b.call_batch ({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', # берем список сделок # и берем список дел по первой из них 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### Call REST API Method Source: https://pypi.org/project/fast-bitrix24/0 A universal method for calling any REST API endpoint. Use this when `get_all` and `get_by_ID` are not suitable. It can handle single parameter dictionaries or lists of parameters for multiple calls. ```APIDOC ## POST /api/call ### Description Calls a specified REST API method with provided parameters. This is a flexible method suitable for various API interactions. ### Method POST ### Endpoint /api/call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (str) - Required - The REST API method to call. - **items** (dict | list) - Required - Parameters for the method. Can be a single dictionary for one call or a list of dictionaries for multiple calls. ### Request Example ```json { "method": "crm.lead.add", "items": {"fields": {"NAME": "Test Lead", "STATUS_ID": "NEW"}} } ``` ```json { "method": "crm.lead.add", "items": [ {"fields": {"NAME": "Lead 1"}}, {"fields": {"NAME": "Lead 2"}} ] } ``` ### Response #### Success Response (200) - **result** (dict | list) - The result of the API call(s). A dictionary for a single call, or a list of results if `items` was a list. #### Response Example ```json { "result": {"ID": "1"} } ``` ```json { "result": [{"ID": "1"}, {"ID": "2"}] } ``` ``` -------------------------------- ### Make a Single API Call with fast_bitrix24 Source: https://pypi.org/project/fast-bitrix24/index This code snippet illustrates how to make a single API call to Bitrix24 using the `call()` method of the `fast_bitrix24` library. It shows that `call()` can accept a single method and its parameters, returning the result for that specific call. For multiple calls, it's recommended to batch them for efficiency. ```python method = 'crm.lead.add' params = {'fields': {'TITLE': 'Чпок'}} bx.call(method, params) ``` -------------------------------- ### Handle Server Errors with Slow Context Manager (Python) Source: https://pypi.org/project/fast-bitrix24/1 Provides a solution for the common issue of receiving server errors when adding multiple leads. By wrapping the `call()` method within the `slow()` context manager, the rate of requests is controlled, allowing the server to process them without errors. This is a practical application of request throttling. ```python with b.slow(): results = b.call('crm.lead.add', tasks) ``` -------------------------------- ### Asynchronous API Calls with BitrixAsync Source: https://pypi.org/project/fast-bitrix24/1 For asynchronous operations, instantiate the `BitrixAsync` class instead of `Bitrix`. All methods in `BitrixAsync` mirror their synchronous counterparts in `Bitrix`, allowing for non-blocking API interactions. ```python from fast_bitrix24 import BitrixAsync b = BitrixAsync(webhook) leads = await b.get_all('crm.lead.list') ``` -------------------------------- ### Python: Perform Batch API Calls with call_batch() Source: https://pypi.org/project/fast-bitrix24/0 The `call_batch()` method allows you to execute multiple Bitrix24 API methods in a single request. It takes a dictionary with 'halt' and 'cmd' parameters, where 'cmd' defines the batch commands. This is useful for reducing the number of HTTP requests and improving performance. ```python results = b.call_batch ({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### Execute Batch Calls with call_batch() Source: https://pypi.org/project/fast-bitrix24/1 The `call_batch()` method is used to execute multiple Bitrix24 API calls in a single request. This is efficient for retrieving related data, such as a list of deals and then activities associated with the first deal. ```python results = b.call_batch ({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', # get list of deals # and get list of activities for the first one 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### Batch API Call Source: https://pypi.org/project/fast-bitrix24/0 Executes multiple REST API commands in a single batch request. Supports using results from one command in subsequent commands via the '$result' keyword. ```APIDOC ## POST /api/call_batch ### Description Executes a batch of REST API calls. This method allows for chaining commands, where the output of one command can be used as input for another. ### Method POST ### Endpoint /api/call_batch ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (dict) - Required - A dictionary defining the batch commands. It should contain 'halt' (0 or 1) and 'cmd' (a dictionary of command names and their corresponding API calls). ### Request Example ```json { "halt": 0, "cmd": { "deals": "crm.deal.list", "activities": "crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]" } } ``` ### Response #### Success Response (200) - **result** (dict) - A dictionary where keys are the command names defined in the request and values are the results of those commands. #### Response Example ```json { "result": { "deals": [...], "activities": [...] } } ``` ``` -------------------------------- ### Fetch All Leads using get_all() in Python Source: https://pypi.org/project/fast-bitrix24/1 Retrieves a list of all leads from the Bitrix24 CRM using the `get_all` method. This method is suitable for fetching complete lists of entities. ```python # list of leads leads = b.get_all('crm.lead.list') ``` -------------------------------- ### call_batch Source: https://pypi.org/project/fast-bitrix24/1 Executes the batch method, allowing multiple commands to be sent in a single request. It supports using results from one command in subsequent commands. ```APIDOC ## POST /batch ### Description Executes the batch method, allowing multiple commands to be sent in a single request. It supports using results from one command in subsequent commands. ### Method POST ### Endpoint /batch ### Parameters #### Request Body - **halt** (integer) - Required - Specifies whether to stop processing commands if an error occurs. - **cmd** (object) - Required - An object where keys are command names and values are the Bitrix24 API method calls. ### Request Example ```json { "halt": 0, "cmd": { "deals": "crm.deal.list", "activities": "crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]" } } ``` ### Response #### Success Response (200) - **command_name_1** (object) - The result of the first command execution. - **command_name_2** (object) - The result of the second command execution. #### Response Example ```json { "deals": [...], "activities": [...] } ``` ``` -------------------------------- ### Batch API Calls Source: https://pypi.org/project/fast-bitrix24/1 Utilize the `call_batch()` method for executing multiple API requests in a single batch operation, improving efficiency. ```APIDOC ## POST /api/call_batch ### Description Executes multiple Bitrix24 API commands in a single batch request. This is efficient for performing several operations at once, potentially with interdependencies between commands. ### Method POST ### Endpoint /api/call_batch ### Parameters #### Request Body - **halt** (int) - Optional - If set to 1, the batch will halt on the first error. Defaults to 0. - **cmd** (dict) - Required - A dictionary where keys are command aliases and values are the Bitrix24 API methods to execute. Can include references to previous command results using `$result[alias][index][field]` syntax. ### Request Example ```json { "halt": 0, "cmd": { "deals": "crm.deal.list", "activities": "crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]" } } ``` ### Response #### Success Response (200) - **result** (dict) - A dictionary containing the results of each command, keyed by the command alias provided in the request. ``` -------------------------------- ### Execute arbitrary calls using call() Source: https://pypi.org/project/fast-bitrix24/index The `call()` method allows for direct execution of Bitrix24 REST API methods, enabling the creation, modification, or deletion of entities. It's a versatile method for operations not covered by higher-level abstractions. ```python # Example of creating a new lead new_lead = bx.call('crm.lead.add', { 'fields': { 'NAME': 'John Doe', 'SECOND_NAME': 'Doe', 'LAST_NAME': 'Doe', 'STATUS_ID': 'NEW', 'OPENED': 'Y', 'ASSIGNED_BY_ID': 1, 'PHONE': [{'VALUE': '5551234567', 'VALUE_TYPE': 'WORK'}], 'EMAIL': [{'VALUE': 'john.doe@example.com', 'VALUE_TYPE': 'WORK'}] } }) ``` -------------------------------- ### Disable SSL Verification with aiohttp ClientSession (Python) Source: https://pypi.org/project/fast-bitrix24/1 Provides a solution for `SSLCertVerificationError` or `CERTIFICATE_VERIFY_FAILED` errors. It demonstrates how to disable SSL certificate verification by initializing an `aiohttp.ClientSession` with `ssl=False` and passing this client instance to `BitrixAsync`. This is a workaround for environments with SSL configuration issues. ```python import aiohttp import asyncio from fast_bitrix24 import BitrixAsync async def main(): # Инициализировать HTTP-клиента без верификации SSL и передать его в `BitrixAsync` connector = aiohttp.TCPConnector(ssl=False) async with aiohttp.ClientSession(connector=connector) as client: b = BitrixAsync(webhook, client=client) # Далее ваши вызовы Битрикса ... asyncio.run(main()) ```