### Initialize the Zoho CRM SDK Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md This class demonstrates the required setup for logging, user authentication, environment selection, token storage, and SDK configuration. ```python from zcrmsdk.src.com.zoho.crm.api.user_signature import UserSignature from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore, FileStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig class SDKInitializer(object): @staticmethod def initialize(): """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance(level=Logger.Levels.INFO, file_path='/Users/user_name/Documents/python_sdk_log.log') # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email='abc@zoho.com') """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> Grant token. 4 -> Refresh token. 5 -> OAuth redirect URL. 6 -> id """ token = OAuthToken(client_id='clientId', client_secret='clientSecret', grant_token='grant_token', refresh_token="refresh_token", redirect_url='redirectURL', id="id") """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ store = FileStore(file_path='/Users/username/Documents/python_sdk_tokens.txt') """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" 6-> DataBase table name . Default value "oauthtoken" """ store = DBStore() store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='password',port_number='port_number', table_name = "table_name") """ auto_refresh_fields (Default value is False) if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation (Default value is True) A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list connect_timeout (Default value is None) A Float field to set connect timeout read_timeout (Default value is None) A Float field to set read timeout """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False, connect_timeout=None, read_timeout=None) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/Users/user_name/Documents/python-app' """ Create an instance of RequestProxy class that takes the following parameters 1 -> Host 2 -> Port Number 3 -> User Name. Default value is None 4 -> Password. Default value is None """ request_proxy = RequestProxy(host='host', port=8080) request_proxy = RequestProxy(host='host', port=8080, user='user', password='password') """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance. Default value is None 8 -> RequestProxy instance. Default value is None """ ``` -------------------------------- ### Implement Multi-threading for Multi-user Apps Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md This example demonstrates how to extend the threading.Thread class to handle concurrent API requests for different users, environments, and proxy settings. ```python import threading from zcrmsdk.src.com.zoho.crm.api.user_signature import UserSignature from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter, EUDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.record import * from zcrmsdk.src.com.zoho.crm.api.request_proxy import RequestProxy from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig class MultiThread(threading.Thread): def __init__(self, environment, token, user, module_api_name, sdk_config, proxy=None): super().__init__() self.environment = environment self.token = token self.user = user self.module_api_name = module_api_name self.sdk_config = sdk_config self.proxy = proxy def run(self): try: Initializer.switch_user(user=self.user, environment=self.environment, token=self.token, sdk_config=self.sdk_config, proxy=self.proxy) print('Getting records for User: ' + Initializer.get_initializer().user.get_email()) response = RecordOperations().get_records(self.module_api_name) if response is not None: # Get the status code from response print('Status Code: ' + str(response.get_status_code())) if response.get_status_code() in [204, 304]: print('No Content' if response.get_status_code() == 204 else 'Not Modified') return # Get object from response response_object = response.get_object() if response_object is not None: # Check if expected ResponseWrapper instance is received. if isinstance(response_object, ResponseWrapper): # Get the list of obtained Record instances record_list = response_object.get_data() for record in record_list: for key, value in record.get_key_values().items(): print(key + " : " + str(value)) # Check if the request returned an exception elif isinstance(response_object, APIException): # Get the Status print("Status: " + response_object.get_status().get_value()) # Get the Code print("Code: " + response_object.get_code().get_value()) print("Details") # Get the details dict details = response_object.get_details() for key, value in details.items(): print(key + ' : ' + str(value)) # Get the Message print("Message: " + response_object.get_message().get_value()) except Exception as e: print(e) @staticmethod def call(): logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") user1 = UserSignature(email="abc@zoho.com") token1 = OAuthToken(client_id="clientId1", client_secret="clientSecret1", grant_token="Grant Token", refresh_token="refresh_token", id="id") environment1 = USDataCenter.PRODUCTION() store = DBStore() sdk_config_1 = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) resource_path = '/Users/user_name/Documents/python-app' user1_module_api_name = 'Leads' user2_module_api_name = 'Contacts' environment2 = EUDataCenter.SANDBOX() user2 = UserSignature(email="abc@zoho.eu") sdk_config_2 = SDKConfig(auto_refresh_fields=False, pick_list_validation=True) token2 = OAuthToken(client_id="clientId2", client_secret="clientSecret2",grant_token="GRANT Token", refresh_token="refresh_token", redirect_url="redirectURL", id="id") request_proxy_user_2 = RequestProxy("host", 8080) Initializer.initialize(user=user1, environment=environment1, token=token1, store=store, sdk_config=sdk_config_1, resource_path=resource_path, logger=logger) t1 = MultiThread(environment1, token1, user1, user1_module_api_name, sdk_config_1) t2 = MultiThread(environment2, token2, user2, user2_module_api_name, sdk_config_2, request_proxy_user_2) t1.start() t2.start() t1.join() t2.join() MultiThread.call() ``` -------------------------------- ### Implement Multi-threading for API Operations Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md This example defines a MultiThread class inheriting from threading.Thread to execute record retrieval concurrently. Ensure the SDK is initialized with valid user credentials and environment settings before starting threads. ```python import threading from zcrmsdk.src.com.zoho.crm.api.user_signature import UserSignature from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig from zcrmsdk.src.com.zoho.crm.api.record import * class MultiThread(threading.Thread): def __init__(self, module_api_name): super().__init__() self.module_api_name = module_api_name def run(self): try: print("Calling Get Records for module: " + self.module_api_name) response = RecordOperations().get_records(self.module_api_name) if response is not None: # Get the status code from response print('Status Code: ' + str(response.get_status_code())) if response.get_status_code() in [204, 304]: print('No Content' if response.get_status_code() == 204 else 'Not Modified') return # Get object from response response_object = response.get_object() if response_object is not None: # Check if expected ResponseWrapper instance is received. if isinstance(response_object, ResponseWrapper): # Get the list of obtained Record instances record_list = response_object.get_data() for record in record_list: for key, value in record.get_key_values().items(): print(key + " : " + str(value)) # Check if the request returned an exception elif isinstance(response_object, APIException): # Get the Status print("Status: " + response_object.get_status().get_value()) # Get the Code print("Code: " + response_object.get_code().get_value()) print("Details") # Get the details dict details = response_object.get_details() for key, value in details.items(): print(key + ' : ' + str(value)) # Get the Message print("Message: " + response_object.get_message().get_value()) except Exception as e: print(e) @staticmethod def call(): logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") user = UserSignature(email="abc@zoho.com") token = OAuthToken(client_id="clientId", client_secret="clientSecret", grant_token="grant_token", refresh_token="refresh_token", redirect_url="redirectURL", id="id") environment = USDataCenter.PRODUCTION() store = DBStore() sdk_config = SDKConfig() resource_path = '/Users/user_name/Documents/python-app' Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=sdk_config, resource_path=resource_path, logger=logger) t1 = MultiThread('Leads') t2 = MultiThread('Quotes') t1.start() t2.start() t1.join() t2.join() MultiThread.call() ``` -------------------------------- ### Install Zoho CRM Python SDK Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Install the Python SDK for Zoho CRM using pip. Ensure you have Python 3 or above installed. ```sh pip install zohocrmsdk2_1==3.x.x ``` -------------------------------- ### Get Notes from Zoho CRM Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Retrieves a list of notes with specified fields, page, and per-page count. Ensure the NotesOperations class is imported. ```python from zcrmsdk.src.com.zoho.crm.api.notes import NotesOperations, GetNotesParam from zcrmsdk.src.com.zoho.crm.api.header import HeaderMap def get_notes(): notes_operations = NotesOperations() param_instance = ParameterMap() param_instance.add(GetNotesParam.page, 1) param_instance.add(GetNotesParam.per_page, 200) param_instance.add(GetNotesParam.fields, "id,Note_Title,Note_Content") response = notes_operations.get_notes(param_instance, HeaderMap()) if response.get_status_code() == 200: notes = response.get_object().get_data() for note in notes: print(f"Note ID: {note.get_id()}") print(f"Title: {note.get_note_title()}") print(f"Content: {note.get_note_content()}") ``` -------------------------------- ### GET /records Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Retrieve records from a specified CRM module. Supports pagination, field selection, and conditional fetching. ```APIDOC ## GET /records Perform CRUD operations on CRM module records (Leads, Contacts, Accounts, Deals, etc.). This specific example demonstrates fetching records. ### Description Retrieve records from a specified CRM module. Supports pagination, field selection, and conditional fetching based on headers like 'If-Modified-Since'. ### Method GET ### Endpoint `/records` (This is a conceptual endpoint; the actual SDK method is `record_operations.get_records(module_api_name, param_instance, header_instance)`) ### Parameters #### Query Parameters - **page** (Integer) - Optional - The page number for pagination. - **per_page** (Integer) - Optional - The number of records to retrieve per page. - **fields** (String) - Optional - A comma-separated list of fields to include in the response. #### Header Parameters - **If-Modified-Since** (DateTime) - Optional - Retrieves records modified since the specified date and time. ### Request Example ```python from zcrmsdk.src.com.zoho.crm.api.record import RecordOperations, GetRecordsParam, GetRecordsHeader from zcrmsdk.src.com.zoho.crm.api import ParameterMap, HeaderMap from datetime import datetime def get_records(module_api_name): record_operations = RecordOperations() param_instance = ParameterMap() # Set pagination and field parameters param_instance.add(GetRecordsParam.page, 1) param_instance.add(GetRecordsParam.per_page, 200) param_instance.add(GetRecordsParam.fields, "Last_Name,Email,Company") header_instance = HeaderMap() header_instance.add(GetRecordsHeader.if_modified_since, datetime.fromisoformat('2023-01-01T00:00:00+00:00')) response = record_operations.get_records(module_api_name, param_instance, header_instance) if response is not None and response.get_status_code() == 200: response_object = response.get_object() if isinstance(response_object, ResponseWrapper): records = response_object.get_data() for record in records: print(f"Record ID: {record.get_id()}") print(f"Created Time: {record.get_created_time()}") # Access field values print(f"Last Name: {record.get_key_value('Last_Name')}") ``` ### Response #### Success Response (200) - **data** (Array of Record objects) - A list of CRM records matching the query. - Each Record object contains fields like `id`, `created_time`, and custom fields. #### Response Example ```json { "data": [ { "id": "123456789012345", "created_time": "2023-10-27T10:00:00+05:30", "Last_Name": "Doe", "Email": "john.doe@example.com", "Company": "Example Corp" } ], "info": { "per_page": 200, "page": 1, "count": 1, "more_records": false } } ``` ``` -------------------------------- ### Get Attachments for a Record Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Retrieves a list of attachments for a specific CRM record, including pagination parameters. Requires importing AttachmentsOperations and GetAttachmentsParam. ```python from zcrmsdk.src.com.zoho.crm.api.attachments import AttachmentsOperations, GetAttachmentsParam def get_attachments(module_api_name, record_id): attachments_operations = AttachmentsOperations(module_api_name, record_id) param_instance = ParameterMap() param_instance.add(GetAttachmentsParam.page, 1) param_instance.add(GetAttachmentsParam.per_page, 20) response = attachments_operations.get_attachments(param_instance) if response.get_status_code() == 200: attachments = response.get_object().get_data() for attachment in attachments: print(f"Attachment ID: {attachment.get_id()}") print(f"File Name: {attachment.get_file_name()}") print(f"Size: {attachment.get_size()}") ``` -------------------------------- ### Get Zoho CRM Records Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Retrieve records for a specified module using pagination, field selection, and conditional headers like 'If-Modified-Since'. Handles response parsing and data extraction. ```python from zcrmsdk.src.com.zoho.crm.api.record import RecordOperations, GetRecordsParam, GetRecordsHeader from zcrmsdk.src.com.zoho.crm.api import ParameterMap, HeaderMap from datetime import datetime def get_records(module_api_name): record_operations = RecordOperations() param_instance = ParameterMap() # Set pagination and field parameters param_instance.add(GetRecordsParam.page, 1) param_instance.add(GetRecordsParam.per_page, 200) param_instance.add(GetRecordsParam.fields, "Last_Name,Email,Company") header_instance = HeaderMap() header_instance.add(GetRecordsHeader.if_modified_since, datetime.fromisoformat('2023-01-01T00:00:00+00:00')) response = record_operations.get_records(module_api_name, param_instance, header_instance) if response is not None and response.get_status_code() == 200: response_object = response.get_object() if isinstance(response_object, ResponseWrapper): records = response_object.get_data() for record in records: print(f"Record ID: {record.get_id()}") print(f"Created Time: {record.get_created_time()}") # Access field values print(f"Last Name: {record.get_key_value('Last_Name')}") ``` -------------------------------- ### SDK Initialization Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Initialize the SDK with OAuth2 credentials and configure the runtime environment before making any API calls. ```APIDOC ## SDK Initialization Initialize the SDK with OAuth2 credentials and configure the runtime environment before making any API calls. ### Method N/A (Initialization) ### Endpoint N/A (Initialization) ### Parameters N/A ### Request Example ```python from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore, FileStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig from zcrmsdk.src.com.zoho.crm.api.request_proxy import RequestProxy # Configure logging logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/app/logs/python_sdk_log.log") # Set up OAuth token with refresh token token = OAuthToken( client_id='your_client_id', client_secret='your_client_secret', refresh_token='your_refresh_token', grant_token=None ) # Choose a token persistence store # Option 1: Database store token_store = DBStore(host='localhost', database_name='zohooauth', user_name='root', password='password', port_number='3306', table_name='oauthtoken') # Option 2: File store token_store = FileStore(file_path='/app/tokens/python_sdk_tokens.txt') # Configure SDK settings sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) # Initialize the SDK Initializer.initialize( environment=USDataCenter.PRODUCTION(), token=token, store=token_store, sdk_config=sdk_config, resource_path='/app/resources', logger=logger ) ``` ### Response N/A (Initialization does not return a response in the typical API sense.) ``` -------------------------------- ### Initialize Zoho CRM SDK Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Initializes the SDK with user, environment, token, store, configuration, resource path, logger, and proxy settings. ```python Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=config, resource_path=resource_path, logger=logger, proxy=request_proxy) ``` -------------------------------- ### Initialize DBStore Object Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate the DBStore class to manage token persistence in a MySQL database. ```python from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore """ DBStore takes the following parameters 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" 6-> DataBase table name . Default value "oauthtoken" """ store = DBStore() store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='password', port_number='port_number', table_name = "table_name") ``` -------------------------------- ### Initialize FileStore Object Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate the FileStore class to persist tokens in a local file. ```python from zcrmsdk.src.com.zoho.api.authenticator.store import FileStore """ FileStore takes the following parameter 1 -> Absolute file path of the file to persist tokens """ store = FileStore(file_path='/Users/username/Documents/python_sdk_token.txt') ``` -------------------------------- ### SDK Initialization Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Initializes the Zoho CRM SDK with user credentials, environment, and configuration. ```APIDOC ## Initializer.initialize ### Description Initializes the SDK environment to enable API functionality. ### Parameters - **user** (User) - Required - User object containing credentials - **environment** (Environment) - Required - The target environment - **token** (Token) - Required - Authentication token - **store** (TokenStore) - Required - Token storage mechanism - **sdk_config** (SDKConfig) - Optional - SDK configuration settings - **resource_path** (str) - Optional - Path to resources - **logger** (Logger) - Optional - Logger instance - **proxy** (RequestProxy) - Optional - Proxy configuration ``` -------------------------------- ### Create SDKConfig Instance Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate SDKConfig to manage SDK settings like auto-refreshing fields, pick list validation, and connection/read timeouts. Default values are provided for each parameter. ```python from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig """ By default, the SDK creates the SDKConfig instance auto_refresh_fields (Default value is False) if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation (Default value is True) A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list connect_timeout (Default value is None) A Float field to set connect timeout read_timeout (Default value is None) A Float field to set read timeout """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False, connect_timeout=None, read_timeout=None) ``` -------------------------------- ### Configure TokenStore Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Configure TokenStore to persist tokens for authentication. The SDK defaults to 'sdk_tokens.txt'. You can use DBStore for database persistence or FileStore for a specific file path. ```python from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore, FileStore """ DBStore takes the following parameters 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" 6 -> DataBase table name. Default value "oauthtoken" """ store = DBStore() #store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='password', port_number='port_number', table_name = "table_name") """ FileStore takes the following parameter 1 -> Absolute file path of the file to persist tokens """ #store = FileStore(file_path='/Users/username/Documents/python_sdk_tokens.txt') ``` -------------------------------- ### Initialize Zoho CRM Python SDK Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Configure the SDK with OAuth2 credentials, token persistence, logging, and environment settings before making API calls. Supports database or file-based token storage. ```python from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore, FileStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig from zcrmsdk.src.com.zoho.crm.api.request_proxy import RequestProxy # Configure logging logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/app/logs/python_sdk_log.log") # Set up OAuth token with refresh token token = OAuthToken( client_id='your_client_id', client_secret='your_client_secret', refresh_token='your_refresh_token', grant_token=None ) # Choose a token persistence store # Option 1: Database store token_store = DBStore(host='localhost', database_name='zohooauth', user_name='root', password='password', port_number='3306', table_name='oauthtoken') # Option 2: File store token_store = FileStore(file_path='/app/tokens/python_sdk_tokens.txt') # Configure SDK settings sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) # Initialize the SDK Initializer.initialize( environment=USDataCenter.PRODUCTION(), token=token, store=token_store, sdk_config=sdk_config, resource_path='/app/resources', logger=logger ) ``` -------------------------------- ### Initialize and Fetch Records with Zoho CRM SDK Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Configures the SDK environment, authentication, and logging before executing a request to retrieve records from a specific module. ```python from datetime import datetime from zcrmsdk.src.com.zoho.crm.api.user_signature import UserSignature from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore from zcrmsdk.src.com.zoho.api.logger import Logger from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken from zcrmsdk.src.com.zoho.crm.api.record import * from zcrmsdk.src.com.zoho.crm.api import HeaderMap, ParameterMap from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig class Record(object): def __init__(self): pass @staticmethod def get_records(): """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email="abc@zoho.com") """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> Grant token. 4 -> Refresh token. 5 -> OAuth redirect URL. 6 -> id """ token = OAuthToken(client_id="clientId", client_secret="clientSecret", grant_token="grant_token", refresh_token="refresh_token", redirect_url="redirectURL", id="id") """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" 6-> DataBase table name . Default value "oauthtoken" """ store = DBStore() """ auto_refresh_fields (Default value is False) if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation (Default value is True) A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list connect_timeout (Default value is None) A Float field to set connect timeout read_timeout (Default value is None) A Float field to set read timeout """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False, connect_timeout=None, read_timeout=None) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/Users/user_name/Documents/python-app' """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance """ Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=config, resource_path=resource_path, logger=logger) try: module_api_name = 'Leads' param_instance = ParameterMap() param_instance.add(GetRecordsParam.converted, 'both') param_instance.add(GetRecordsParam.cvid, '12712717217218') header_instance = HeaderMap() header_instance.add(GetRecordsHeader.if_modified_since, datetime.now()) response = RecordOperations().get_records(module_api_name, param_instance, header_instance) if response is not None: # Get the status code from response ``` -------------------------------- ### Implement Custom TokenStore Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Create a custom persistence layer by extending the TokenStore base class and overriding its methods. ```python from zcrmsdk.src.com.zoho.api.authenticator.store import TokenStore class CustomStore(TokenStore): def __init__(self): pass def get_token(self, user, token): """ Parameters: user (UserSignature) : A UserSignature class instance. token (Token) : A Token (zcrmsdk.src.com.zoho.api.authenticator.OAuthToken) class instance """ # Add code to get the token return None def save_token(self, user, token): """ Parameters: user (UserSignature) : A UserSignature class instance. token (Token) : A Token (zcrmsdk.src.com.zoho.api.authenticator.OAuthToken) class instance """ # Add code to save the token def delete_token(self, token): """ Parameters: token (Token) : A Token (zcrmsdk.src.com.zoho.api.authenticator.OAuthToken) class instance """ # Add code to delete the token def get_tokens(self): """ Returns: list: List of stored tokens """ # Add code to get all the stored tokens def delete_tokens(self): # Add code to delete all the stored tokens def get_token_by_id(id, token): """ The method to get id token details. Parameters: id (String) : A String id. token (Token) : A Token class instance. Returns: Token : A Token class instance representing the id token details. """ ``` -------------------------------- ### SDK Configuration Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Create an instance of SDKConfig to manage SDK-specific settings like auto-refresh fields, pick list validation, and connection timeouts. ```APIDOC ## SDK Configuration ### Description Create an instance of `SDKConfig` containing SDK configurations. - `auto_refresh_fields` (Default value is False) - if True - all the modules' fields will be auto-refreshed in the background, every hour. - if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from `ModuleFieldsHandler`. - `pick_list_validation` (Default value is True) - A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. - if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. - if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list. - `connect_timeout` (Default value is None) - A Float field to set connect timeout. - `read_timeout` (Default value is None) - A Float field to set read timeout. ### Method Instantiate `SDKConfig` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from zcrmsdk.src.com.zoho.crm.api.sdk_config import SDKConfig config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False, connect_timeout=None, read_timeout=None) ``` ``` -------------------------------- ### Configure Proxy for User Switching Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Use this method to switch the active user context while applying a proxy configuration. ```python Initializer.switch_user(user=user, environment=environment, token=token, sdk_config=sdk_config_instance, proxy=request_proxy) ``` -------------------------------- ### Create and Retrieve Bulk Read Jobs in Python Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Functions to initiate a bulk read job with specific criteria and retrieve the status or download URL of an existing job. ```python from zcrmsdk.src.com.zoho.crm.api.bulk_read import BulkReadOperations, RequestWrapper, Query, Criteria, CallBack def create_bulk_read_job(module_api_name): bulk_read_operations = BulkReadOperations() request = RequestWrapper() # Configure the query query = Query() query.set_module(module_api_name) query.set_page(1) # Set criteria for filtering criteria = Criteria() criteria.set_group_operator("or") criteria_list = [] # First criterion criterion1 = Criteria() criterion1.set_api_name("Created_Time") criterion1.set_comparator("between") criterion1.set_value(["2023-01-01T00:00:00+00:00", "2023-12-31T23:59:59+00:00"]) criteria_list.append(criterion1) # Second criterion criterion2 = Criteria() criterion2.set_api_name("Owner") criterion2.set_comparator("equal") criterion2.set_value(347706112716001) criteria_list.append(criterion2) criteria.set_group(criteria_list) query.set_criteria(criteria) # Specify fields to export query.set_fields(["Last_Name", "First_Name", "Email", "Company", "Created_Time"]) request.set_query(query) # Set callback URL for notification callback = CallBack() callback.set_url("https://your-app.com/webhook/bulk-read-complete") callback.set_method("post") request.set_callback(callback) response = bulk_read_operations.create_bulk_read_job(request) if response.get_status_code() in [200, 201]: job_details = response.get_object().get_data()[0].get_details() job_id = job_details.get('id') print(f"Bulk Read Job Created: {job_id}") return job_id def get_bulk_read_job_details(job_id): bulk_read_operations = BulkReadOperations() response = bulk_read_operations.get_bulk_read_job_details(job_id) if response.get_status_code() == 200: job = response.get_object().get_data()[0] print(f"Job State: {job.get_state().get_value()}") result = job.get_result() if result is not None: print(f"Download URL: {result.get_download_url()}") ``` -------------------------------- ### Create RequestProxy Instance Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate RequestProxy to manage proxy server connections. This involves providing the host and port, with optional user name and password for authentication. ```python from zcrmsdk.src.com.zoho.crm.api.request_proxy import RequestProxy request_proxy = RequestProxy(host='proxyHost', port=80) ``` ```python request_proxy = RequestProxy(host='proxyHost', port=80, user='userName', password='password') ``` -------------------------------- ### Configure API Environment Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Configure the API environment to specify the domain and URL for API calls. Available domains include USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, and AUDataCenter, with environments like PRODUCTION(), DEVELOPER(), and SANDBOX(). ```python from zcrmsdk.src.com.zoho.crm.api.dc import USDataCenter """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() ``` -------------------------------- ### Token Store Configuration Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Configure a TokenStore to persist tokens, which are used for authenticating all requests. Supports DBStore and FileStore. ```APIDOC ## Token Store Configuration ### Description Create an instance of `TokenStore` to persist tokens, used for authenticating all the requests. By default, the SDK creates the `sdk_tokens.txt` (created in the current working directory) to persist the tokens. ### Method Instantiate `DBStore` or `FileStore` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from zcrmsdk.src.com.zoho.api.authenticator.store import DBStore, FileStore # DBStore takes the following parameters # 1 -> DataBase host name. Default value "localhost" # 2 -> DataBase name. Default value "zohooauth" # 3 -> DataBase user name. Default value "root" # 4 -> DataBase password. Default value "" # 5 -> DataBase port number. Default value "3306" # 6 -> DataBase table name. Default value "oauthtoken" store = DBStore() #store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='password', port_number='port_number', table_name = "table_name") # FileStore takes the following parameter # 1 -> Absolute file path of the file to persist tokens #store = FileStore(file_path='/Users/username/Documents/python_sdk_tokens.txt') ``` ``` -------------------------------- ### Create UserSignature Instance Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate UserSignature to identify the current user by their email address. This is a mandatory key for SDK initialization. ```python from zcrmsdk.src.com.zoho.crm.api.user_signature import UserSignature # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email='abc@zoho.com') ``` -------------------------------- ### Configure Logger Instance Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate the Logger class to log exceptions and API information. By default, it logs at INFO level to 'sdk_logs.log'. You can specify the log level and file path. ```python from zcrmsdk.src.com.zoho.api.logger import Logger """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") ``` -------------------------------- ### Response Handling Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Explains the structure of API responses returned by the SDK. ```APIDOC ## API Response Handling ### Description All SDK methods return an APIResponse instance. The get_object() method returns specific wrapper classes based on the request type. ### GET Request Wrappers - **ResponseWrapper** - **CountWrapper** - **DeletedRecordsWrapper** - **MassUpdateResponseWrapper** - **FileBodyWrapper** (for file downloads) - **APIException** (on error) ### POST, PUT, DELETE Request Wrappers - **ActionWrapper** - **RecordActionWrapper** - **BaseCurrencyActionWrapper** - **MassUpdateActionWrapper** - **ConvertActionWrapper** - **APIException** (on error) ``` -------------------------------- ### Create OAuthToken Instance Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Create an OAuthToken instance using credentials obtained after registering your Zoho client. This includes client ID, client secret, grant token, refresh token, and redirect URL. ```python from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> Grant token. 4 -> Refresh token. 5 -> OAuth redirect URL. Default value is None 6 -> id 7 -> Access token """ token = OAuthToken(client_id='clientId', client_secret='clientSecret', grant_token='grant_token', refresh_token="refresh_token", redirect_url='redirectURL', id="id", access_token="access_token") ``` -------------------------------- ### Create Notes in Zoho CRM Source: https://context7.com/zoho/zohocrm-python-sdk-2.1/llms.txt Creates new notes and optionally links them to a parent record. Requires importing NotesOperations, BodyWrapper, and ZCRMNote. ```python from zcrmsdk.src.com.zoho.crm.api.notes import NotesOperations, BodyWrapper from zcrmsdk.src.com.zoho.crm.api.notes.note import Note as ZCRMNote from zcrmsdk.src.com.zoho.crm.api.record import Record def create_notes(): notes_operations = NotesOperations() request = BodyWrapper() notes_list = [] note = ZCRMNote() note.set_note_title('Follow-up Required') note.set_note_content('Need to schedule a follow-up call next week.') # Link note to a parent record parent_record = Record() parent_record.set_id(34096432267003) note.set_parent_id(parent_record) note.set_se_module('Leads') notes_list.append(note) request.set_data(notes_list) response = notes_operations.create_notes(request) ``` -------------------------------- ### Logger Configuration Source: https://github.com/zoho/zohocrm-python-sdk-2.1/blob/master/README.md Instantiate a Logger Class to log exceptions and API information. You can configure the log level and file path. ```APIDOC ## Logger Configuration ### Description Create an instance of `Logger` Class to log exception and API information. By default, the SDK constructs a Logger instance with level - INFO and file_path - (sdk_logs.log, created in the current working directory). ### Method Get instance of `Logger` using `Logger.get_instance()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from zcrmsdk.src.com.zoho.api.logger import Logger # Create an instance of Logger Class that takes two parameters # 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. # 2 -> Absolute file path, where messages need to be logged. logger = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") ``` ```