### Install B24PySDK Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Install the SDK using pip. For optional signal support, use the `signals` extra. ```bash pip install b24pysdk ``` ```bash pip install "b24pysdk[signals]" ``` -------------------------------- ### Install b24pysdk with FastAPI extra Source: https://github.com/bitrix24/b24pysdk/blob/main/b24pysdk/integrations/fastapi/README.md Install the SDK with the necessary extra for FastAPI integration. ```bash pip install "b24pysdk[fastapi]" ``` -------------------------------- ### Parameter Handling Example Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-SCOPES-CREATION-README.md Demonstrates how to handle 'select' parameters, ensuring they are always lists before being added to the params dictionary. ```python params: JSONDict = {} if select is not None: if select.__class__ is not list: select = list(select) params["select"] = select ``` -------------------------------- ### Install B24PYSDK with Django Extra Source: https://github.com/bitrix24/b24pysdk/blob/main/b24pysdk/integrations/django/README.md Install the SDK with the Django extra package using pip. ```bash pip install "b24pysdk[django]" ``` -------------------------------- ### Install Flask Extra Source: https://github.com/bitrix24/b24pysdk/blob/main/b24pysdk/integrations/flask/README.md Install the b24pysdk with the Flask extra dependency. ```bash pip install "b24pysdk[flask]" ``` -------------------------------- ### Install b24pysdk with Signals Extra Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Install the b24pysdk with the optional 'signals' extra to enable event subscription functionality. This is required for handling events like OAuth token renewal and portal domain changes. ```bash pip install "b24pysdk[signals]" ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/bitrix24/b24pysdk/blob/main/DEV-RUN-TEST-README.md Install development dependencies using pip. Ensure you have a requirements-dev.txt file. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Get Lead Product Rows Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_productrows_get.md This example demonstrates how to retrieve product rows for a given lead ID using the Bitrix24 Python SDK. It includes error handling for API and SDK exceptions. ```APIDOC ## crm.lead.productrows.get ### Description Returns product rows linked to a lead. ### Method GET (or equivalent SDK call) ### Endpoint (Not directly applicable for SDK, but conceptually related to CRM leads) ### Parameters #### Query Parameters - **id** (integer) - Required - The unique identifier of the lead. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.lead.productrows.get( bitrix_id=1201, ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ### Response #### Success Response (200) - **result** (array) - An array of product-row objects associated with the lead. ### Response Example (The actual JSON response structure for product-row objects would be detailed here if provided in the source) ### Notes `crm.lead.productrows.get` is not list-capable, so `.as_list()` and `.as_list_fast()` are not applicable. ``` -------------------------------- ### Workgroup Entity Wrapper Example Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-SCOPES-CREATION-README.md Provides an example of a Workgroup entity wrapper class, including 'get' and 'list' methods with type checking and parameter processing. ```python # b24pysdk/scopes/socialnetwork/workgroup.py from typing import Iterable, Optional, Text from ...api.requests import BitrixAPIRequest from ...utils.converters import bool_to_bitrix from ...utils.functional import type_checker from ...utils.types import JSONDict, Timeout from .._base_entity import BaseEntity __all__ = [ "Workgroup", ] class Workgroup(BaseEntity): '''''' @type_checker def get( self, params: JSONDict, *, timeout: Timeout = None, ) -> BitrixAPIRequest: '''''' params: JSONDict = { "params": params, } return self._make_bitrix_api_request( api_wrapper=self.get, params=params, timeout=timeout, ) @type_checker def list( self, *, filter: Optional[JSONDict] = None, select: Optional[Iterable[Text]] = None, is_admin: Optional[bool] = None, timeout: Timeout = None, ) -> BitrixAPIRequest: '''''' params: JSONDict = {} if filter is not None: params["filter"] = filter if select is not None: if select.__class__ is not list: select = list(select) params["select"] = select if is_admin is not None: params["IS_ADMIN"] = bool_to_bitrix(is_admin, is_required=True) return self._make_bitrix_api_request( api_wrapper=self.list, params=params, timeout=timeout, ) ``` -------------------------------- ### Retrieve as List Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_recurring_list.md This example shows how to retrieve the recurring deal templates as a flat list using the `.as_list()` method, which simplifies iteration over the results. ```APIDOC ## crm.deal.recurring.list (as_list) ### Description Returns a filtered list of recurring deal templates, processed into a flat list. ### Method Signature `client.crm.deal.recurring.list(select: list, filter: dict, order: dict).as_list().response` ### Parameters #### Query Parameters - **select** (list) - Required - Fields to include in the response. - **filter** (dict) - Optional - Criteria to filter the recurring deals. - **order** (dict) - Optional - Order of the recurring deals. ### Response Shape `result` is a list of recurring template objects. ### Request Example (Python SDK) ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.recurring.list( select=["ID", "DEAL_ID", "ACTIVE"], filter={"=ACTIVE": "Y"}, order={"ID": "ASC"}, ).as_list().response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### Update Lead Example (Python SDK) Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_update.md Use this snippet to update an existing lead's details. Ensure you have the `BaseClient` initialized and handle potential `BitrixAPIError` and `BitrixSDKException`. ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException from datetime import datetime client: BaseClient updated_birthdate = datetime(1989, 7, 14).date().isoformat() try: bitrix_response = client.crm.lead.update( bitrix_id=1201, fields={ "TITLE": "Acme Industrial Subscription - Negotiation", "STATUS_ID": "IN_PROCESS", "OPPORTUNITY": 27500.0, "CURRENCY_ID": "USD", "ASSIGNED_BY_ID": 1, "COMMENTS": "Budget approved, waiting for legal review.", "SOURCE_DESCRIPTION": "Updated after discovery workshop", "BIRTHDATE": updated_birthdate, "PHONE": [{"VALUE": "+12025550120", "VALUE_TYPE": "WORK"}], "EMAIL": [{"VALUE": "procurement@acme-industrial.com", "VALUE_TYPE": "WORK"}], "WEB": [{"VALUE": "https://acme-industrial.com/contact", "VALUE_TYPE": "WORK"}], "UTM_SOURCE": "linkedin", "UTM_MEDIUM": "paid-social", "UTM_CAMPAIGN": "enterprise_followup", "UTM_CONTENT": "case_study_ad", "UTM_TERM": "crm rollout", }, params={"REGISTER_SONET_EVENT": "Y"}, ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` -------------------------------- ### CRM Lead List - as_list Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_list.md Shows how to use the `.as_list()` method to retrieve leads, which is suitable for iterating through results directly. Includes basic filtering and ordering. ```APIDOC ## crm.lead.list - as_list Example ### Description Retrieves a list of leads and formats the response as a Python list directly. This method is useful for simple iteration over results. ### Method `client.crm.lead.list().as_list()` ### Parameters - **select** (list) - Required - List of fields to retrieve for each lead. - **filter** (dict) - Optional - Criteria to filter leads. Example: `{'!STATUS_ID': 'JUNK'}` - **order** (dict) - Optional - Specifies the order of the results. Example: `{'ID': 'ASC'}` ### Response - **result** (list) - A list of lead objects matching the filter criteria. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.lead.list( select=["ID", "TITLE", "STATUS_ID"], filter={"!STATUS_ID": "JUNK"}, order={"ID": "ASC"}, ).as_list().response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### Retrieve User Fields as a List (Python) Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/user.userfield/user_userfield_list.md This example demonstrates how to fetch user fields and process them as a Python list. It's useful when you need to iterate over the results. ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException order = { "ID": "desc", } filter = { "SHOW_IN_LIST": "Y", } try: bitrix_response = client.user.userfield.list( order=order, filter=filter, ).as_list().response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print("Bitrix SDK error", error.message, sep="\n") except Exception as error: print("Unexpected error", error, sep="\n") ``` -------------------------------- ### Class Docstring Example Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-SCOPES-DOC-CREATION-README.md Use this template for class docstrings. The first line should be a short summary, followed by a blank line and a link to official documentation. ```python """ Handle operations related to Bitrix24 workgroups. Documentation: https://apidocs.bitrix24.com/api-reference/sonet-group/index.html """ ``` -------------------------------- ### Retrieve as Fast List Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_recurring_list.md This example demonstrates using `.as_list_fast()` for potentially faster retrieval of recurring deal templates as a flat list, with an option to specify descending order. ```APIDOC ## crm.deal.recurring.list (as_list_fast) ### Description Returns a filtered list of recurring deal templates as a flat list, optimized for speed. ### Method Signature `client.crm.deal.recurring.list(select: list, filter: dict, order: dict).as_list_fast(descending: bool = True).response` ### Parameters #### Query Parameters - **select** (list) - Required - Fields to include in the response. - **filter** (dict) - Optional - Criteria to filter the recurring deals. - **order** (dict) - Optional - Order of the recurring deals. - **descending** (bool) - Optional - If True, sorts in descending order. Defaults to True. ### Response Shape `result` is a list of recurring template objects. ### Request Example (Python SDK) ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.recurring.list( select=["ID", "DEAL_ID", "ACTIVE"], filter={"=ACTIVE": "Y"}, order={"ID": "DESC"}, ).as_list_fast(descending=True).response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### CRM Lead List - as_list_fast Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_list.md Demonstrates the use of `.as_list_fast()` for potentially faster retrieval of lead lists, especially when ordering is important. It supports a `descending` parameter. ```APIDOC ## crm.lead.list - as_list_fast Example ### Description Retrieves a list of leads using a potentially faster method optimized for ordered results. The `descending` parameter can be used to control the sort order. ### Method `client.crm.lead.list().as_list_fast()` ### Parameters - **select** (list) - Required - List of fields to retrieve for each lead. - **filter** (dict) - Optional - Criteria to filter leads. Example: `{'!STATUS_ID': 'JUNK'}` - **order** (dict) - Optional - Specifies the order of the results. Example: `{'ID': 'DESC'}` - **descending** (bool) - Optional - If True, results are returned in descending order. Defaults to False. ### Response - **result** (list) - A list of lead objects matching the filter criteria. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.lead.list( select=["ID", "TITLE", "STATUS_ID"], filter={"!STATUS_ID": "JUNK"}, order={"ID": "DESC"}, ).as_list_fast(descending=True).response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### CRM Deal List - Regular Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_list.md Demonstrates how to retrieve a list of deals with specific fields, filters, and ordering. Handles potential API and SDK errors. ```APIDOC ## crm.deal.list - Regular Example ### Description Retrieves a list of CRM deals with specified fields, filters, and ordering. This method is suitable for general use and includes error handling for API and SDK exceptions. ### Method `client.crm.deal.list()` ### Parameters - `select` (list of strings) - Required - Fields to include in the response (e.g., `["ID", "TITLE", "STAGE_ID"]`). - `filter` (dict) - Optional - Criteria to filter deals (e.g., `{'>OPPORTUNITY': 1000, '!STAGE_ID': 'WON'}`). - `order` (dict) - Optional - Specifies the sorting order for the results (e.g., `{"DATE_CREATE": "DESC"}`). - `start` (int) - Optional - The index of the first deal to return for pagination. ### Response - `result` (list of dict) - A list of deal objects matching the criteria. - Paging fields like `total` and `next` may be included. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.list( select=["ID", "TITLE", "STAGE_ID", "OPPORTUNITY", "ASSIGNED_BY_ID", "DATE_CREATE"], filter=">{'>OPPORTUNITY': 1000, '!STAGE_ID': 'WON', '=OPENED': 'Y'},", order={"DATE_CREATE": "DESC", "ID": "DESC"}, start=0, ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### CRM Deal List - as_list Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_list.md Shows how to retrieve deals and process them directly as a Python list, useful for iterating through results without manual pagination handling. ```APIDOC ## crm.deal.list - as_list Example ### Description Retrieves a list of CRM deals and formats the response directly as a Python list. This method simplifies iteration over results, especially when dealing with a large number of deals. ### Method `client.crm.deal.list().as_list()` ### Parameters - `select` (list of strings) - Required - Fields to include in the response. - `filter` (dict) - Optional - Criteria to filter deals. - `order` (dict) - Optional - Specifies the sorting order for the results. ### Response - `result` (list of dict) - A list of deal objects. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.list( select=["ID", "TITLE", "STAGE_ID"], filter={"!STAGE_ID": "LOSE"}, order={"ID": "ASC"}, ).as_list().response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### Run Application Bridge Source: https://github.com/bitrix24/b24pysdk/blob/main/DEV-RUN-TEST-README.md Start the application bridge using FastAPI's development server. This is required for certain integration tests. ```bash fastapi dev tests/application_bridge/index.py ``` -------------------------------- ### CRM Deal List - as_list_fast Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_list.md Provides an optimized way to retrieve deals as a list, suitable for scenarios requiring faster data retrieval, with an option for descending order. ```APIDOC ## crm.deal.list - as_list_fast Example ### Description Retrieves CRM deals in a list format using an optimized method for faster data fetching. This method is particularly useful when performance is critical and allows specifying descending order directly. ### Method `client.crm.deal.list().as_list_fast(descending=True)` ### Parameters - `select` (list of strings) - Required - Fields to include in the response. - `filter` (dict) - Optional - Criteria to filter deals. - `order` (dict) - Optional - Specifies the sorting order for the results. - `descending` (bool) - Optional - If True, results are returned in descending order. ### Response - `result` (list of dict) - A list of deal objects, potentially in descending order. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.list( select=["ID", "TITLE", "STAGE_ID"], filter={"!STAGE_ID": "LOSE"}, order={"ID": "DESC"}, ).as_list_fast(descending=True).response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### Get list of tasks Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Demonstrates how to retrieve a list of tasks using the `tasks.task.list` method. Ensure you use only real method parameters from the SDK signature. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of tasks result = bx24.tasks.task.list({'filter': {'REAL_STATUSES': [1, 2, 3, 4, 5]}}) print(result) ``` -------------------------------- ### Create Deal from Recurring Template Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_recurring_expose.md This example demonstrates how to use the `crm.deal.recurring.expose` method to create a deal from a recurring template. It includes error handling for potential API or SDK exceptions. ```APIDOC ## crm.deal.recurring.expose ### Description Creates a deal from a recurring template. ### Method Signature `client.crm.deal.recurring.expose(bitrix_id: int)` ### Parameters #### Path Parameters - **bitrix_id** (int) - Required - The ID of the recurring deal template. ### Response Shape `result` is an object that includes `DEAL_ID` for the created deal. ### Request Example (Python SDK) ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.recurring.expose(bitrix_id=77).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ### Response Example ```json { "result": { "DEAL_ID": 12345 } } ``` ### Notes `crm.deal.recurring.expose` is not list-capable in SDK usage, so `.as_list()` and `.as_list_fast()` examples are not applicable. ``` -------------------------------- ### Configure Local Environment Variables Source: https://github.com/bitrix24/b24pysdk/blob/main/DEV-RUN-TEST-README.md Set up your local environment by creating a .env.local file with Bitrix24 portal credentials and authentication details. This is crucial for local testing. ```txt B24_DOMAIN=b24-e4f2d1.bitrix24.com B24_WEBHOOK=13/dd5w3aldjdu4twfk B24_CLIENT_ID=local.672f30763b63d4.04393872 B24_CLIENT_SECRET=rdsfdcc6RtwHlkFng5145gGdhebdh8mXl12QjaD112frtBSL16 B24_PREFER_AUTH_TYPE=webhook # Only if you're running the integration tests directly, without first running tests/application_bridge/index.py B24_ACCESS_TOKEN=b0872d69007e1212107f3e254fb7f1gdsgdv11297667cf03e675caa B24_REFRESH_TOKEN=a00655dgghd5tfd25df256fd52e5f1f5d60d44b7bd193be0a98869 B24_EXPIRES=2025-11-28 21:09:16+03:00 B24_EXPIRES_IN=3600 B24_EXPIRED_TOKEN=expired_token_value ``` -------------------------------- ### Retrieve All Deals using as_list() Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Shows how to retrieve the full list of deals by using the `.as_list()` method on a list query. ```python request = client.crm.deal.list() deals = request.as_list().result # full list of records ``` -------------------------------- ### Get a single CRM deal by ID (API v3) Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieve a specific CRM deal using its ID with API v3. This example demonstrates the error handling specific to API v3, including validation errors. ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixSDKException from b24pysdk.errors.v3 import BitrixAPIError try: bitrix_response = client.crm.deal.get( id=1 ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API v3 error", f"code: {error.code}", f"message: {error.error.message}", sep="\n", ) if error.has_validation: print(f"validation: {error.validation}") except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` -------------------------------- ### Update Deal Example - Python SDK Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_update.md Use this snippet to update an existing deal's fields and parameters. Ensure you have a `BaseClient` instance initialized. Handles potential Bitrix API and SDK errors. ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.update( bitrix_id=123, fields={ "TITLE": "Enterprise License Renewal - Negotiation", "STAGE_ID": "PREPARATION", "OPPORTUNITY": 28000, "COMMENTS": "Updated after discovery call", "ASSIGNED_BY_ID": 1, }, params={"REGISTER_SONET_EVENT": "Y", "REGISTER_HISTORY_EVENT": "Y"}, ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` -------------------------------- ### Get (Retrieve a Record) Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-README.md Fetches details for a specific entity by its ID or a unique key. ```APIDOC ## Get (Retrieve a Record) ### Description Fetches details for a specific entity by its ID or a unique key and retrieves its field values. ### Method `client.crm.currency.get()` ### Parameters #### Query Parameters - **bitrix_id** (string) - Required - The Bitrix ID of the currency to retrieve. ### Request Example ```python try: currency = client.crm.currency.get(bitrix_id="USD").result print(currency["LANG"]["de"]["FORMAT_STRING"], currency["LANG"]["de"]["DEC_POINT"]) except BitrixAPIError as error: print(f"API Bitrix error {error.error: {error}}") except Exception as error: print(f"Error: {error}") ``` ### Response #### Success Response (200) - **LANG** (object) - Contains language-specific information about the currency. - **de** (object) - German language details. - **FORMAT_STRING** (string) - The format string for the currency. - **DEC_POINT** (string) - The decimal point character. #### Response Example ```json { "LANG": { "de": { "FORMAT_STRING": "$", "DEC_POINT": "," } } } ``` ``` -------------------------------- ### Get lead details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Fetches the details of a specific lead using its ID with the `crm.lead.get` method. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get lead details result = bx24.crm.lead.get({'ID': 1}) print(result) ``` -------------------------------- ### CRM Lead List - Regular Example Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_list.md Demonstrates how to retrieve a list of leads with specific fields, filters, and ordering using the Python SDK. Includes error handling for API and SDK exceptions. ```APIDOC ## crm.lead.list - Regular Example ### Description Returns a filtered and ordered list of leads with specified fields. This example shows basic usage with select, filter, order, and start parameters. ### Method `client.crm.lead.list()` ### Parameters - **select** (list) - Required - List of fields to retrieve for each lead. - **filter** (dict) - Optional - Criteria to filter leads. Example: `{'>OPPORTUNITY': 0, '!STATUS_ID': 'CONVERTED', '=OPENED': 'Y'}` - **order** (dict) - Optional - Specifies the order of the results. Example: `{'DATE_CREATE': 'DESC', 'ID': 'DESC'}` - **start** (int) - Optional - The index of the first record to retrieve for pagination. ### Response - **result** (list) - A list of lead objects matching the filter criteria. ### Request Example ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.lead.list( select=["ID", "TITLE", "STATUS_ID", "OPPORTUNITY", "CURRENCY_ID", "ASSIGNED_BY_ID", "DATE_CREATE"], filter=">{'>OPPORTUNITY': 0, '!STATUS_ID': 'CONVERTED', '=OPENED': 'Y'}", order={"DATE_CREATE": "DESC", "ID": "DESC"}, start=0, ).response result = bitrix_response.result print(result) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` ``` -------------------------------- ### Get company details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Fetches the details of a specific company using its ID with the `crm.company.get` method. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get company details result = bx24.crm.company.get({'ID': 1}) print(result) ``` -------------------------------- ### Get deal details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Fetches the details of a specific deal using its ID with the `crm.deal.get` method. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get deal details result = bx24.crm.deal.get({'ID': 1}) print(result) ``` -------------------------------- ### Get contact details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Fetches the details of a specific contact using its ID with the `crm.contact.get` method. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get contact details result = bx24.crm.contact.get({'ID': 1}) print(result) ``` -------------------------------- ### Get Deal by ID Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Demonstrates how to retrieve a specific deal by its Bitrix24 ID using the `crm.deal.get` method. ```python request = client.crm.deal.get(bitrix_id=2) ``` -------------------------------- ### Fetch Recurring Deal List as a Python List Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_recurring_list.md This example shows how to use the `.as_list()` method to directly retrieve the results as a Python list. It's useful for iterating through the items without manual pagination handling. ```python from b24pysdk.client import BaseClient from b24pysdk.errors import BitrixAPIError, BitrixSDKException client: BaseClient try: bitrix_response = client.crm.deal.recurring.list( select=["ID", "DEAL_ID", "ACTIVE"], filter={"=ACTIVE": "Y"}, order={"ID": "ASC"}, ).as_list().response result = bitrix_response.result for item in result: print(item) except BitrixAPIError as error: print( "Bitrix API error", f"error: {error.error}", f"error_description: {error.error_description}", sep="\n", ) except BitrixSDKException as error: print(f"Bitrix SDK error: {error.message}") except Exception as error: print(f"Unexpected error: {error}") ``` -------------------------------- ### Get CRM Lead Contact Fields Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.lead/crm_lead_contact_fields.md Retrieves metadata for lead-contact relation fields. This method is not list-capable. ```APIDOC ## crm.lead.contact.fields ### Description Returns metadata for lead-contact relation fields. ### Method GET (or equivalent SDK call) ### Endpoint /crm.lead.contact.fields ### Parameters None ### Request Example ```python client.crm.lead.contact.fields() ``` ### Response #### Success Response (200) - **result** (object) - An object describing relation fields such as `CONTACT_ID`, `SORT`, and `IS_PRIMARY`. ### Response Example ```json { "result": { "CONTACT_ID": { "type": "integer", "is_required": "Y", "is_read_only": "N", "is_multiple": "N" }, "SORT": { "type": "integer", "is_required": "N", "is_read_only": "N", "is_multiple": "N" }, "IS_PRIMARY": { "type": "char", "is_required": "N", "is_read_only": "N", "is_multiple": "N" } } } ``` ``` -------------------------------- ### Get list of leads Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves a list of leads using the `crm.lead.list` method. Filtering and sorting options are available. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of leads result = bx24.crm.lead.list({'filter': {'LAST_NAME': 'Doe'}}) print(result) ``` -------------------------------- ### Get Entity Fields Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-README.md Retrieves the fields for a specified entity type. This is useful for understanding the available properties of an entity. ```APIDOC ## Get Entity Fields ### Description Retrieves the fields for a specified entity type. This is useful for understanding the available properties of an entity. ### Method `client.crm.item.fields()` ### Parameters #### Query Parameters - **entity_type_id** (int) - Required - The ID of the entity type. - **use_original_uf_names** (string) - Optional - Use 'Y' or 'N' to specify if original user field names should be used. ### Request Example ```python try: request = client.crm.item.fields( entity_type_id=1268, use_original_uf_names="N", ).result print(request["webformId"]["title"]) except BitrixAPIError as error: print(f"API Bitrix error {error.error: {error}}") except Exception as error: print(f"Error: {error}") ``` ### Response #### Success Response (200) - **webformId** (object) - Contains information about the webform ID, including its title. - **title** (string) - The title of the webform. #### Response Example ```json { "webformId": { "title": "Webform Title" } } ``` ``` -------------------------------- ### Get list of companies Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves a list of companies using the `crm.company.list` method. Filtering and sorting options are available. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of companies result = bx24.crm.company.list({'filter': {'TITLE': 'New Company'}}) print(result) ``` -------------------------------- ### Initialize Client with Default API Version Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Instantiate the Client class with an authenticated token. If no API version is specified, it defaults to v2. ```python from b24pysdk import Client client = Client(bitrix_token) ``` -------------------------------- ### Get list of contacts Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves a list of contacts using the `crm.contact.list` method. Filtering and sorting options are available. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of contacts result = bx24.crm.contact.list({'filter': {'LAST_NAME': 'Doe'}}) print(result) ``` -------------------------------- ### Get list of deals Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves a list of deals using the `crm.deal.list` method. You can filter, sort, and select specific fields. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of deals result = bx24.crm.deal.list({'filter': {'CONTACT_ID': 1}}) print(result) ``` -------------------------------- ### Update Deal Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_update.md This example demonstrates how to update an existing deal by providing its ID and a dictionary of fields to modify. It also shows how to include optional parameters for registering events and handling potential API or SDK errors. ```APIDOC ## crm.deal.update ### Description Updates an existing deal. ### Method `client.crm.deal.update(bitrix_id: int, fields: dict, params: dict = None)` ### Parameters #### Path Parameters - **bitrix_id** (int) - Required - The unique identifier of the deal to update. #### Request Body - **fields** (dict) - Required - A dictionary containing the fields to update. Supported fields include: - `TITLE` (string) - `STAGE_ID` (string) - `OPPORTUNITY` (float) - `COMMENTS` (string) - `ASSIGNED_BY_ID` (int) - **params** (dict) - Optional - A dictionary for additional parameters, such as: - `REGISTER_SONET_EVENT` (string: "Y" or "N") - `REGISTER_HISTORY_EVENT` (string: "Y" or "N") ### Request Example ```python client.crm.deal.update( bitrix_id=123, fields={ "TITLE": "Enterprise License Renewal - Negotiation", "STAGE_ID": "PREPARATION", "OPPORTUNITY": 28000, "COMMENTS": "Updated after discovery call", "ASSIGNED_BY_ID": 1, }, params={ "REGISTER_SONET_EVENT": "Y", "REGISTER_HISTORY_EVENT": "Y", }, ) ``` ### Response #### Success Response (200) - **result** (boolean) - `true` if the update was successful. ``` -------------------------------- ### Call CRM Deal Fields Method Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Example of calling a specific API method, crm.deal.fields, to retrieve deal field descriptions. ```python request = client.crm.deal.fields() ``` -------------------------------- ### Retrieve All Deals Efficiently using as_list_fast() Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Demonstrates using the optimized `.as_list_fast()` method for retrieving large datasets of deals, with lazy loading. ```python request = client.crm.deal.list() deals = request.as_list_fast().result # generator for deal in deals: # requests are made lazily during iteration print(deal["TITLE"]) ``` -------------------------------- ### Get user details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Fetches details for a specific user using their ID with the `user.get` method. Pass the user ID in the parameters. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get user details result = bx24.user.get({'ID': 1}) print(result) ``` -------------------------------- ### Get list of users Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves a list of users from Bitrix24 using the `user.get` method. This method can be filtered by various user properties. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get list of users result = bx24.user.get({'filter': {'ACTIVE': True}}) print(result) ``` -------------------------------- ### Retrieve Deals (Default Limit) Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Demonstrates retrieving a list of deals, which by default returns up to 50 records. ```python request = client.crm.deal.list() deals = request.result # up to 50 records ``` -------------------------------- ### Get task details Source: https://github.com/bitrix24/b24pysdk/blob/main/instructions/AI-PROMPT-SCOPES-METHOD-EXAMPLES.md Retrieves the details of a specific task using its ID with the `tasks.task.get` method. This returns the full task object. ```python from b24.bitrix24 import Bitrix24 bx24 = Bitrix24('YOUR_WEBHOOK_URL') # Get task details result = bx24.tasks.task.get({'ID': 1}) print(result) ``` -------------------------------- ### Initialize BitrixTokenLocal Authentication (Local Apps) Source: https://github.com/bitrix24/b24pysdk/blob/main/README.md Use BitrixTokenLocal for local app authentication. Requires app credentials and authorization/refresh tokens. ```python from b24pysdk import BitrixTokenLocal, BitrixAppLocal bitrix_app = BitrixAppLocal( domain="example.bitrix24.com", client_id="app_code", client_secret="app_key", ) bitrix_token = BitrixTokenLocal( auth_token="auth_token_of_the_app", refresh_token="refresh_token_of_the_app", # optional parameter bitrix_app=bitrix_app, ) ``` -------------------------------- ### Test User List Retrieval with as_list() Source: https://github.com/bitrix24/b24pysdk/blob/main/AI-SCOPES-TEST-CREATION-README.md Uses the .as_list() method to fetch users and asserts the response is a BitrixAPIListResponse containing a list of dictionaries. Requires 'test_user_add' to be run first. ```python @pytest.mark.dependency(name="test_user_get_as_list", depends=["test_user_add"]) def test_user_get_as_list(bitrix_client: BaseClient): """""" bitrix_response = bitrix_client.user.get().as_list().response assert isinstance(bitrix_response, BitrixAPIListResponse) assert isinstance(bitrix_response.result, list) users = bitrix_response.result assert len(users) >= 1, "Expected at least one user to be returned" for user in users: assert isinstance(user, dict) ``` -------------------------------- ### Delete Contact Bindings from Deal Source: https://github.com/bitrix24/b24pysdk/blob/main/examples/scopes/crm.deal/crm_deal_contact_items_delete.md This example demonstrates how to delete all contact bindings from a CRM deal by providing the deal's Bitrix ID. ```APIDOC ## crm.deal.contact.items.delete ### Description Deletes all contact bindings from a deal. ### Method Signature `client.crm.deal.contact.items.delete(bitrix_id: int)` ### Parameters #### Path Parameters - **bitrix_id** (int) - Required - The ID of the deal from which to delete contact bindings. ### Request Example ```python # Assuming 'client' is an initialized Bitrix24 client instance result = client.crm.deal.contact.items.delete(bitrix_id=123).response.result print(result) ``` ### Response #### Success Response (200) - **result** (boolean) - Returns `true` if the operation was successful. ```