### Install and Upgrade Zoho CRM SDK Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Commands to install or upgrade the SDK package using pip. ```bash pip install zcrmsdk ``` ```bash pip install --upgrade zcrmsdk ``` -------------------------------- ### Fetch Zoho CRM Module Metadata Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Retrieve information about CRM modules, fields, layouts, and custom views. This example demonstrates fetching all modules, details of a specific module, module fields, layouts, and custom views. Error handling for API exceptions is included. ```python from zcrmsdk.RestClient import ZCRMRestClient from zcrmsdk.Operations import ZCRMModule from zcrmsdk.CLException import ZCRMException try: client = ZCRMRestClient.get_instance() # Get all modules in the CRM response = client.get_all_modules() for module in response.data: print(f"Module: {module.api_name}, Label: {module.plural_label}") # Get specific module with full details module_response = client.get_module('Contacts') contacts_module = module_response.data print(f"Module ID: {contacts_module.id}") print(f"Creatable: {contacts_module.is_creatable}") print(f"Editable: {contacts_module.is_editable}") # Get module instance for operations (no API call) module_ins = ZCRMModule.get_instance('Leads') # Get all fields for a module fields_response = module_ins.get_all_fields() for field in fields_response.data: print(f"Field: {field.api_name}, Type: {field.data_type}, Required: {field.is_mandatory}") # Get all layouts layouts_response = module_ins.get_all_layouts() for layout in layouts_response.data: print(f"Layout: {layout.name}, ID: {layout.id}") # Get custom views views_response = module_ins.get_all_customviews() for view in views_response.data: print(f"View: {view.display_value}, Default: {view.is_default}") except ZCRMException as ex: print(f"Error Code: {ex.error_code}") print(f"Error Message: {ex.error_message}") print(f"Details: {ex.error_details}") ``` -------------------------------- ### Initialize SDK Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Invoke this statement at the startup of the client application to initialize the SDK. ```python ZCRMRestClient.initialize(configuration_dictionary) ``` -------------------------------- ### Create Records with Line Items in Python Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Demonstrates how to instantiate line items, associate taxes, and create records in a module. Ensure the record instance is prepared before calling create_records. ```python line_item=ZCRMInventoryLineItem.get_instance(ZCRMRecord.get_instance("Products",440872000000224005)) line_item.discount=10 line_item.list_price=8 line_item.description='Product Description' line_item.quantity=100 line_item.tax_amount=2.5 taxIns=ZCRMTax.get_instance("Vat") taxIns.percentage=5 line_item.line_tax.append(taxIns) record.add_line_item(line_item) record_ins_list.append(record) resp=ZCRMModule.get_instance('Invoices').create_records(record_ins_list) print resp.status_code entity_responses=resp.bulk_entity_response for entity_response in entity_responses: print entity_response.details print entity_response.status print entity_response.message print entity_response.code print entity_response.data.entity_id print entity_response.data.created_by.id print entity_response.data.created_time print entity_response.data.modified_by.id except ZCRMException as ex: print ex.status_code print ex.error_message print ex.error_code print ex.error_details print ex.error_content ``` -------------------------------- ### Manage Organization Taxes with Python SDK Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt This snippet demonstrates how to manage organization tax configurations, including retrieval, creation, update, and deletion of taxes. Ensure the ZCRMRestClient is initialized. ```python from zcrmsdk.RestClient import ZCRMRestClient from zcrmsdk.Operations import ZCRMOrgTax from zcrmsdk.CLException import ZCRMException try: client = ZCRMRestClient.get_instance() org = client.get_organization_instance() # Get all organization taxes taxes_response = org.get_organization_taxes() for tax in taxes_response.data: print(f"Tax: {tax.name}") print(f" ID: {tax.id}") print(f" Value: {tax.value}%") print(f" Display Label: {tax.display_label}") # Get specific tax tax_id = 4876543210000000111 tax_response = org.get_organization_tax(tax_id) tax = tax_response.data print(f"Tax Details: {tax.name} - {tax.value}%") # Create new taxes new_taxes = [] tax1 = ZCRMOrgTax.get_instance(name='State Tax') tax1.value = 6.5 new_taxes.append(tax1) tax2 = ZCRMOrgTax.get_instance(name='County Tax') tax2.value = 1.25 new_taxes.append(tax2) create_response = org.create_organization_taxes(new_taxes) for entity_resp in create_response.bulk_entity_response: print(f"Created Tax: {entity_resp.data.name}, ID: {entity_resp.data.id}") # Update taxes taxes_to_update = [] tax_update = ZCRMOrgTax.get_instance(org_tax_id=4876543210000000111, name='State Tax') tax_update.value = 7.0 taxes_to_update.append(tax_update) update_response = org.update_organization_taxes(taxes_to_update) print(f"Taxes Updated: {update_response.status_code}") # Delete single tax delete_response = org.delete_organization_tax(4876543210000000222) print(f"Tax Deleted: {delete_response.status}") # Delete multiple taxes tax_ids = [4876543210000000333, 4876543210000000444] bulk_delete = org.delete_organization_taxes(tax_ids) print(f"Bulk Delete: {bulk_delete.status_code}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Configure Zoho CRM SDK Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Sample configuration dictionary containing mandatory OAuth and persistence settings for initializing the ZCRMRestClient. ```python configuration_dictionary = { 'apiBaseUrl':'https://www.zohoapis.com', 'apiVersion':'v2', 'currentUserEmail':'email@gmail.com' 'sandbox':'False' 'applicationLogFilePath':'', 'client_id':'1000.3xxxxxxxxxxxxxxxxxxxxxxxxX0YW', 'client_secret':'29xxxxxxxxxxxxxxxxxxxxxxxxxxxxx7e32', 'redirect_uri':'https://www.abc.com', 'accounts_url':'https://accounts.zoho.com', 'token_persistence_path':'/Users/Zoho/Desktop/PythonSDK/FilePersistence', 'access_type':'online', //Use the below keys for MySQL DB persistence 'mysql_username':'', 'mysql_password':'', 'mysql_port':'3306', //Use the below keys for custom DB persistence 'persistence_handler_class' : 'Custom', 'persistence_handler_path': '/Users/Zoho/Desktop/PythonSDK/CustomPersistance.py' } ``` -------------------------------- ### Manage Record Photos in Python Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Upload, download, and delete profile photos for Leads and Contacts. Requires a valid record instance and local file path for uploads. ```python from zcrmsdk.Operations import ZCRMRecord from zcrmsdk.CLException import ZCRMException try: # Photos are supported for Leads and Contacts modules record = ZCRMRecord.get_instance('Contacts', 4876543210987654321) # Upload photo photo_path = '/path/to/profile-photo.jpg' upload_response = record.upload_photo(photo_path) print(f"Photo Upload Status: {upload_response.status}") print(f"Message: {upload_response.message}") # Download photo download_response = record.download_photo() # Save photo to file with open(f'/downloads/contact_photo.jpg', 'wb') as f: for chunk in download_response.get_response_stream().iter_content(chunk_size=8192): f.write(chunk) print(f"Photo downloaded: {download_response.file_name}") # Delete photo delete_response = record.delete_photo() print(f"Photo Delete Status: {delete_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Set Sandbox and User Email Configuration Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Specific configuration keys for enabling sandbox mode and setting the current user email. ```python 'sandbox':'true' ``` ```python 'currentUserEmail':'user@email.com' ``` -------------------------------- ### Initialize Zoho CRM Python SDK Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Initialize the SDK with OAuth credentials and configuration settings before making any API calls. This must be called once at application startup. For multi-user authentication, set the user email per thread. ```python import zcrmsdk from zcrmsdk.RestClient import ZCRMRestClient from zcrmsdk.OAuthClient import ZohoOAuth # Configuration dictionary with OAuth and persistence settings configuration_dictionary = { 'apiBaseUrl': 'https://www.zohoapis.com', 'apiVersion': 'v2', 'currentUserEmail': 'user@example.com', 'sandbox': 'False', 'applicationLogFilePath': '/path/to/logs', 'client_id': '1000.XXXXXXXXXXXXXXXXXXXX', 'client_secret': '29xxxxxxxxxxxxxxxxxxxxxxxx7e32', 'redirect_uri': 'https://www.yourapp.com/callback', 'accounts_url': 'https://accounts.zoho.com', # File-based token persistence (recommended for single-user apps) 'token_persistence_path': '/path/to/token/storage', 'access_type': 'offline' } # Initialize the SDK - must be called once at application startup ZCRMRestClient.initialize(configuration_dictionary) # For multi-user authentication, set user email per thread import threading threading.current_thread().__setattr__('current_user_email', 'user@example.com') ``` -------------------------------- ### Manage Blueprint Transitions Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Retrieves available blueprint transitions for a record and executes updates by setting required fields and checklist values. ```python from zcrmsdk.Operations import ZCRMRecord from zcrmsdk.CLException import ZCRMException try: # Get record with blueprint record = ZCRMRecord.get_instance('Deals', 4876543210987654321) # Get available blueprint transitions blueprint_response = record.get_blueprint() blueprint = blueprint_response.data # Access process info print("Process Info:") for key, value in blueprint.get_processinfo_values().items(): print(f" {key}: {value}") # List available transitions print("\nAvailable Transitions:") for transition in blueprint.transitions: print(f"Transition: {transition.get_transition_value('name')}") print(f" ID: {transition.get_transition_value('id')}") # Show required fields for this transition for field in transition.fields: required = "Required" if field.is_mandatory else "Optional" print(f" Field: {field.api_name} ({required})") # Show next possible transitions for next_trans in transition.next_transitions: print(f" Next: {next_trans.name}") # Update blueprint (execute transition) record_to_update = ZCRMRecord.get_instance('Deals', 4876543210987654321) record_to_update.blueprint_transition_id = 4876543210000000888 # Set required field values for the transition record_to_update.set_blueprint_data('Stage', 'Negotiation') record_to_update.set_blueprint_data('Amount', 75000) # Set checklist items if required record_to_update.set_checklist_value('Proposal sent', True) record_to_update.set_checklist_value('Contract reviewed', True) update_response = record_to_update.update_blueprint() print(f"Blueprint Updated: {update_response.status_code}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Manage Organization and User Settings Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Retrieve organization details and manage user accounts, roles, and profiles. Requires an initialized ZCRMRestClient instance. ```python from zcrmsdk.RestClient import ZCRMRestClient from zcrmsdk.Operations import ZCRMUser, ZCRMRole, ZCRMProfile from zcrmsdk.CLException import ZCRMException try: client = ZCRMRestClient.get_instance() # Get organization details org_response = client.get_organization_details() org = org_response.data print(f"Organization: {org.company_name}") print(f"Org ID: {org.org_id}") print(f"Time Zone: {org.time_zone}") print(f"Currency: {org.currency_symbol}") # Get organization instance for user management org_ins = client.get_organization_instance() # Get current user current_user_response = org_ins.get_current_user() user = current_user_response.data print(f"Current User: {user.full_name}") print(f"Email: {user.email}") print(f"Role: {user.role.name}") print(f"Profile: {user.profile.name}") # Get all users with pagination users_response = org_ins.get_all_users(page=1, per_page=100) for u in users_response.data: print(f"User: {u.full_name}, Status: {u.status}") # Get specific user types active_users = org_ins.get_all_active_users() admin_users = org_ins.get_all_admin_users() # Get all roles roles_response = org_ins.get_all_roles() for role in roles_response.data: print(f"Role: {role.name}, ID: {role.id}") if role.reporting_to: print(f" Reports to: {role.reporting_to.name}") # Get all profiles profiles_response = org_ins.get_all_profiles() for profile in profiles_response.data: print(f"Profile: {profile.name}, Default: {profile.is_default}") # Create new user new_user = ZCRMUser.get_instance() new_user.first_name = 'Jane' new_user.last_name = 'Smith' new_user.email = 'jane.smith@example.com' new_user.role = ZCRMRole.get_instance(4876543210000000222) new_user.profile = ZCRMProfile.get_instance(4876543210000000333) create_user_response = org_ins.create_user(new_user) print(f"User Created: {create_user_response.data.id}") # Update user user_to_update = ZCRMUser.get_instance(4876543210000000444) user_to_update.phone = '+1-555-1234' update_response = org_ins.update_user(user_to_update) print(f"User Updated: {update_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Import SDK Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Include this import statement in Python files to access SDK functionalities. ```python import zcrmsdk ``` -------------------------------- ### Convert Leads in Python Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Convert Lead records into Contacts, Accounts, and optionally Deals. Supports optional assignment to specific users during conversion. ```python from zcrmsdk.Operations import ZCRMRecord, ZCRMUser from zcrmsdk.CLException import ZCRMException try: # Get Lead to convert lead = ZCRMRecord.get_instance('Leads', 4876543210000000999) # Simple conversion (creates Contact and Account) convert_response = lead.convert() converted_data = convert_response.data print(f"Contact ID: {converted_data.get('Contacts')}") print(f"Account ID: {converted_data.get('Accounts')}") # Conversion with Deal creation potential = ZCRMRecord.get_instance('Deals') potential.set_field_value('Deal_Name', 'Converted Deal') potential.set_field_value('Stage', 'Qualification') potential.set_field_value('Closing_Date', '2024-12-31') potential.set_field_value('Amount', 50000) # Optionally assign to a user assign_to = ZCRMUser.get_instance(4876543210000000001, 'Sales Rep') convert_with_deal = lead.convert( potential_record=potential, assign_to_user=assign_to ) result = convert_with_deal.data print(f"Contact ID: {result.get('Contacts')}") print(f"Account ID: {result.get('Accounts')}") print(f"Deal ID: {result.get('Deals')}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Create CRM Records (Single, Bulk, Invoice with Line Items) Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Use this to create single or multiple records in any CRM module. Supports complex objects like invoices with line items and taxes. Ensure the SDK is initialized. ```python from zcrmsdk.Operations import ZCRMModule, ZCRMRecord, ZCRMUser from zcrmsdk.Operations import ZCRMInventoryLineItem, ZCRMTax from zcrmsdk.CLException import ZCRMException try: # Create a single Contact record contact = ZCRMRecord.get_instance('Contacts') contact.set_field_value('First_Name', 'John') contact.set_field_value('Last_Name', 'Doe') contact.set_field_value('Email', 'john.doe@example.com') contact.set_field_value('Phone', '+1-555-0123') contact.set_field_value('Mailing_City', 'San Francisco') contact.set_field_value('Mailing_State', 'CA') contact.set_field_value('Mailing_Country', 'USA') # Set owner (optional) owner = ZCRMUser.get_instance(4876543210000000001, 'Admin User') contact.set_field_value('Owner', owner) response = contact.create() print(f"Created Record ID: {response.data.entity_id}") print(f"Status: {response.status}") # Bulk create records module_ins = ZCRMModule.get_instance('Leads') record_list = [] for i in range(5): lead = ZCRMRecord.get_instance('Leads') lead.set_field_value('Last_Name', f'Lead {i}') lead.set_field_value('Company', f'Company {i}') lead.set_field_value('Email', f'lead{i}@example.com') record_list.append(lead) bulk_response = module_ins.create_records(record_list) print(f"Bulk Status Code: {bulk_response.status_code}") for entity_response in bulk_response.bulk_entity_response: print(f"Record ID: {entity_response.data.entity_id}") print(f"Status: {entity_response.status}, Code: {entity_response.code}") # Create Invoice with line items invoice = ZCRMRecord.get_instance('Invoices') invoice.set_field_value('Subject', 'Invoice #001') invoice.set_field_value('Account_Name', 'Acme Corp') # Add product line item product = ZCRMRecord.get_instance('Products', 4876543210000000099) line_item = ZCRMInventoryLineItem.get_instance(product) line_item.list_price = 100.00 line_item.quantity = 5 line_item.discount = 10 line_item.description = 'Premium Widget' # Add tax to line item tax = ZCRMTax.get_instance('Sales Tax') tax.percentage = 8.5 line_item.line_tax.append(tax) invoice.add_line_item(line_item) invoice_response = invoice.create() print(f"Invoice ID: {invoice_response.data.entity_id}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") print(f"Details: {ex.error_details}") ``` -------------------------------- ### Implement Custom Token Persistence Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Extend AbstractZohoOAuthPersistence to create custom storage solutions like Redis for OAuth tokens. Update the configuration dictionary to point to your custom class and file path. ```python from zcrmsdk.OAuthClient import AbstractZohoOAuthPersistence, ZohoOAuthTokens class RedisTokenPersistence(AbstractZohoOAuthPersistence): """Custom persistence handler storing tokens in Redis""" def __init__(self): import redis self.redis_client = redis.Redis( host='localhost', port=6379, db=0, decode_responses=True ) self.token_prefix = 'zoho_oauth:' def get_oauthtokens(self, user_email): """Retrieve tokens for a user""" key = f"{self.token_prefix}{user_email}" token_data = self.redis_client.hgetall(key) if not token_data: raise Exception(f"No tokens found for {user_email}") return ZohoOAuthTokens( refresh_token=token_data.get('refresh_token'), access_token=token_data.get('access_token'), expiry_time=int(token_data.get('expiry_time', 0)), user_email=user_email ) def save_oauthtokens(self, oauth_tokens): """Save tokens for a user""" key = f"{self.token_prefix}{oauth_tokens.userEmail}" self.redis_client.hset(key, mapping={ 'refresh_token': oauth_tokens.refreshToken, 'access_token': oauth_tokens.accessToken, 'expiry_time': str(oauth_tokens.expiryTime) }) # Set expiry on the key (30 days) self.redis_client.expire(key, 60 * 60 * 24 * 30) def delete_oauthtokens(self, user_email): """Delete tokens for a user""" key = f"{self.token_prefix}{user_email}" self.redis_client.delete(key) # Configuration to use custom persistence configuration_dictionary = { 'client_id': '1000.XXXXXXXXXXXXXXXXXXXX', 'client_secret': '29xxxxxxxxxxxxxxxxxxxxxxxx7e32', 'redirect_uri': 'https://www.yourapp.com/callback', 'accounts_url': 'https://accounts.zoho.com', 'persistence_handler_class': 'RedisTokenPersistence', 'persistence_handler_path': '/path/to/custom_persistence.py', 'access_type': 'offline' } ``` -------------------------------- ### Fetch CRM Records with Pagination and Filtering Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Use this to retrieve records from any CRM module. Supports pagination, sorting, and filtering. Ensure the SDK is initialized before use. ```python from zcrmsdk.Operations import ZCRMModule, ZCRMRecord from zcrmsdk.CLException import ZCRMException try: # Get module instance module_ins = ZCRMModule.get_instance('Contacts') # Fetch records with pagination response = module_ins.get_records( cvid=None, # Custom view ID (optional) sort_by='Created_Time', sort_order='desc', page=1, per_page=100 ) print(f"Status Code: {response.status_code}") print(f"More Records: {response.info.is_more_records}") print(f"Total Count: {response.info.count}") # Iterate through records for record in response.data: print(f"ID: {record.entity_id}") print(f"Created: {record.created_time}") print(f"Owner: {record.owner.name if record.owner else 'N/A'}") # Access field values dynamically first_name = record.get_field_value('First_Name') last_name = record.get_field_value('Last_Name') email = record.get_field_value('Email') print(f"Name: {first_name} {last_name}, Email: {email}") # Access all field data for field_name, value in record.field_data.items(): print(f" {field_name}: {value}") # Fetch single record by ID record_ins = ZCRMRecord.get_instance('Contacts', 4876543210987654321) single_response = record_ins.get() contact = single_response.data print(f"Contact: {contact.get_field_value('Full_Name')}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Blueprint Management API Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Retrieve and update blueprint transitions for process automation. ```APIDOC ## Blueprint Management Retrieve and update blueprint transitions for process automation. ### Method GET, PUT ### Endpoint `/deals/{deal_id}/blueprint` (example for Deals module) ### Parameters #### Path Parameters - **deal_id** (long) - Required - The ID of the Deal record. #### Request Body (for PUT / Update Blueprint) - **blueprint_transition_id** (long) - Required - The ID of the blueprint transition to execute. - **field_data** (object) - Optional - Key-value pairs for fields required by the transition. - **field_api_name** (string) - The API name of the field. - **value** (any) - The value for the field. - **checklist_data** (object) - Optional - Key-value pairs for checklist items. - **checklist_name** (string) - The name of the checklist item. - **completed** (boolean) - Whether the checklist item is completed. ### Request Example (Get Blueprint) ```python from zcrmsdk.Operations import ZCRMRecord record = ZCRMRecord.get_instance('Deals', 4876543210987654321) blueprint_response = record.get_blueprint() ``` ### Request Example (Update Blueprint) ```python from zcrmsdk.Operations import ZCRMRecord record_to_update = ZCRMRecord.get_instance('Deals', 4876543210987654321) record_to_update.blueprint_transition_id = 4876543210000000888 record_to_update.set_blueprint_data('Stage', 'Negotiation') record_to_update.set_blueprint_data('Amount', 75000) record_to_update.set_checklist_value('Proposal sent', True) update_response = record_to_update.update_blueprint() ``` ### Response #### Success Response (200) - **data** (object) - Blueprint information. - **processinfo** (object) - Information about the current process. - **transitions** (array) - List of available transitions. - **name** (string) - The name of the transition. - **id** (long) - The ID of the transition. - **fields** (array) - Fields required for the transition. - **api_name** (string) - The API name of the field. - **is_mandatory** (boolean) - Whether the field is mandatory. - **next_transitions** (array) - List of subsequent transitions. - **name** (string) - The name of the next transition. - **status_code** (integer) - The status code of the update operation. #### Response Example (Get Blueprint) ```json { "data": { "processinfo": {"name": "Deal Process"}, "transitions": [ { "name": "Start Negotiation", "id": 4876543210000000888, "fields": [ {"api_name": "Stage", "is_mandatory": true}, {"api_name": "Amount", "is_mandatory": true} ], "next_transitions": [{"name": "Send Proposal"}] } ] } } ``` #### Response Example (Update Blueprint) ```json { "status_code": 200 } ``` ``` -------------------------------- ### Generate Access Token via Grant Token Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Use this one-time process to generate an access token from a grant token. The resulting tokens are automatically persisted. ```python ZCRMRestClient.initialize(configuration_dictionary) oauth_client = ZohoOAuth.get_client_instance() grant_token="paste_grant_token_here" oauth_tokens = oauth_client.generate_access_token(grant_token) ``` -------------------------------- ### Fetch Records from a Module in Python Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Retrieves all records from a specified module and iterates through their field data. Requires a valid module API name. ```python try: module_ins=ZCRMModule.get_instance('Products') #module API Name resp=module_ins.get_records() print resp.status_code record_ins_arr=resp.data for record_ins in record_ins_arr: print record_ins.entity_id print record_ins.owner.id print record_ins.created_by.id print record_ins.modified_by.id print record_ins.created_time print record_ins.modified_time product_data=record_ins.field_data for key in product_data: print key+":"+str(product_data[key]) except ZCRMException as ex: print ex.status_code print ex.error_message print ex.error_code print ex.error_details print ex.error_content ``` -------------------------------- ### Generate Access Token via Refresh Token Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Use this one-time process to generate an access token from a refresh token. Requires a user identifier such as an email address. ```python ZCRMRestClient.initialize(configuration_dictionary) oauth_client = ZohoOAuth.get_client_instance() refresh_token="paste_refresh_token_here" user_identifier="provide_user_identifier_like_email_here" oauth_tokens = oauth_client.generate_access_token_from_refresh_token(refresh_token,user_identifier) ``` -------------------------------- ### Search Zoho CRM Records with Python SDK Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Search records in Zoho CRM using various methods: keyword search across all fields, specific searches by email or phone number, and advanced criteria-based searches using COQL-like syntax. Supports pagination for large result sets. Ensure correct module and search parameters are used. ```python from zcrmsdk.Operations import ZCRMModule from zcrmsdk.CLException import ZCRMException try: module_ins = ZCRMModule.get_instance('Contacts') # Search by keyword (searches across all fields) response = module_ins.search_records('John', page=1, per_page=50) print(f"Found {len(response.data)} contacts matching 'John'") for record in response.data: print(f" {record.get_field_value('Full_Name')}") # Search by email email_response = module_ins.search_records_by_email( 'john@example.com', page=1, per_page=10 ) for record in email_response.data: print(f"Email match: {record.entity_id}") # Search by phone phone_response = module_ins.search_records_by_phone( '+1-555', page=1, per_page=10 ) for record in phone_response.data: print(f"Phone match: {record.get_field_value('Phone')}") # Search by criteria (COQL-style) # Format: (field_api_name:operator:value) criteria = "((Last_Name:equals:Doe)and(Lead_Status:equals:Contacted))" criteria_response = module_ins.search_records_by_criteria( criteria, page=1, per_page=100 ) print(f"Criteria matches: {len(criteria_response.data)}") # Complex criteria with OR complex_criteria = "(((City:equals:San Francisco)or(City:equals:New York))and(Annual_Revenue:greater_than:100000))" complex_response = module_ins.search_records_by_criteria(complex_criteria) for record in complex_response.data: print(f" {record.get_field_value('Account_Name')}: ${record.get_field_value('Annual_Revenue')}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Insert Zoho CRM Records Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Use this code to insert multiple records into a Zoho CRM module. Ensure you have the correct module API name and field API names. The `get_instance()` method is used to create dummy objects for modules and users. ```python try: record_ins_list=list() for i in range(0,2): record=ZCRMRecord.get_instance('Invoices') #module API Name record.set_field_value('Subject', 'Invoice'+str(i)) record.set_field_value('Account_Name', 'IIIT') user=ZCRMUser.get_instance(440872000000175001,'Python Automation User1') record.set_field_value('Owner',user) ``` -------------------------------- ### Manage CRM Variables with Python SDK Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Use this snippet to perform CRUD operations on CRM variables. Ensure the ZCRMRestClient is initialized and authenticated. ```python from zcrmsdk.RestClient import ZCRMRestClient from zcrmsdk.Operations import ZCRMVariable, ZCRMVariableGroup from zcrmsdk.CLException import ZCRMException try: client = ZCRMRestClient.get_instance() org = client.get_organization_instance() # Get all variable groups groups_response = org.get_variable_groups() for group in groups_response.data: print(f"Variable Group: {group.name}") print(f" API Name: {group.api_name}") print(f" Display Label: {group.display_label}") # Get all variables variables_response = org.get_variables() for var in variables_response.data: print(f"Variable: {var.name}") print(f" Type: {var.type}") print(f" Value: {var.value}") print(f" Group: {var.variable_group.get('name', 'N/A')}") # Get specific variable var_instance = ZCRMVariable.get_instance() var_instance.id = 4876543210000000111 var_response = var_instance.get_variable(group='General') variable = var_response.data print(f"Variable Value: {variable.value}") # Create new variables new_vars = [] var1 = ZCRMVariable.get_instance() var1.name = 'API_Endpoint' var1.api_name = 'API_Endpoint' var1.type = 'text' var1.value = 'https://api.example.com/v2' var1.variable_group = {'id': 4876543210000000001} new_vars.append(var1) create_response = org.create_variables(new_vars) for entity_resp in create_response.bulk_entity_response: print(f"Created Variable: {entity_resp.data.name}") # Update variable var_to_update = ZCRMVariable.get_instance() var_to_update.id = 4876543210000000111 var_to_update.value = 'https://api.example.com/v3' update_response = var_to_update.update_variable() print(f"Variable Updated: {update_response.status}") # Delete variable var_to_delete = ZCRMVariable.get_instance() var_to_delete.id = 4876543210000000222 delete_response = var_to_delete.delete_variable() print(f"Variable Deleted: {delete_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Manage CRM Record Notes Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Handles creation, retrieval, updating, and deletion of notes associated with a specific CRM record. ```python from zcrmsdk.Operations import ZCRMRecord, ZCRMNote from zcrmsdk.CLException import ZCRMException try: # Get record instance record = ZCRMRecord.get_instance('Contacts', 4876543210987654321) # Create and add a new note note = ZCRMNote.get_instance(record) note.title = 'Follow-up Required' note.content = 'Customer requested callback next week regarding renewal.' response = record.add_note(note) created_note = response.data print(f"Note ID: {created_note.id}") print(f"Created By: {created_note.created_by.name}") # Get all notes for a record notes_response = record.get_notes( sort_by='Modified_Time', sort_order='desc', page=1, per_page=20 ) for note in notes_response.data: print(f"Note: {note.title}") print(f" Content: {note.content}") print(f" Created: {note.created_time}") # Update an existing note existing_note = ZCRMNote.get_instance(record, note_id=4876543210000000555) existing_note.title = 'Updated Title' existing_note.content = 'Updated content with new information.' update_response = record.update_note(existing_note) print(f"Update Status: {update_response.status}") # Delete a note note_to_delete = ZCRMNote.get_instance(record, note_id=4876543210000000555) delete_response = record.delete_note(note_to_delete) print(f"Delete Status: {delete_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Manage Related Lists and Junction Records in Python Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Retrieve related records and manage many-to-many relationships using junction records. Use ZCRMJunctionRecord to link entities like Products and Price Books. ```python from zcrmsdk.Operations import ZCRMRecord, ZCRMJunctionRecord from zcrmsdk.CLException import ZCRMException try: # Get Account record account = ZCRMRecord.get_instance('Accounts', 4876543210000000123) # Get related Contacts for this Account related_response = account.get_relatedlist_records( relatedlist_api_name='Contacts', sort_by='Created_Time', sort_order='desc', page=1, per_page=50 ) print(f"Related Contacts: {len(related_response.data)}") for contact in related_response.data: print(f" {contact.get_field_value('Full_Name')} - {contact.get_field_value('Email')}") # Get related Deals deals_response = account.get_relatedlist_records('Deals') for deal in deals_response.data: print(f"Deal: {deal.get_field_value('Deal_Name')} - ${deal.get_field_value('Amount')}") # Add relation (Many-to-Many relationship via junction) product = ZCRMRecord.get_instance('Products', 4876543210000000456) # Create junction record to link Product with Price Book junction = ZCRMJunctionRecord.get_instance('Price_Books', 4876543210000000789) junction.set_related_data('list_price', 99.99) add_response = product.add_relation(junction) print(f"Relation Added: {add_response.status}") # Remove relation remove_junction = ZCRMJunctionRecord.get_instance('Price_Books', 4876543210000000789) remove_response = product.remove_relation(remove_junction) print(f"Relation Removed: {remove_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Manage Tags on Records and Modules Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Perform CRUD operations on tags and associate them with records or modules. Requires importing ZCRMModule, ZCRMRecord, and ZCRMTag from the operations module. ```python from zcrmsdk.Operations import ZCRMModule, ZCRMRecord, ZCRMTag from zcrmsdk.CLException import ZCRMException try: module_ins = ZCRMModule.get_instance('Contacts') # Get all tags for a module tags_response = module_ins.get_tags() for tag in tags_response.data: print(f"Tag: {tag.name}, ID: {tag.id}, Count: {tag.count}") # Create new tags new_tags = [] tag1 = ZCRMTag.get_instance(name='VIP Customer') new_tags.append(tag1) tag2 = ZCRMTag.get_instance(name='Priority Support') new_tags.append(tag2) create_response = module_ins.create_tags(new_tags) for entity_resp in create_response.bulk_entity_response: print(f"Created Tag: {entity_resp.data.name}, ID: {entity_resp.data.id}") # Add tags to a single record record = ZCRMRecord.get_instance('Contacts', 4876543210987654321) add_tag_response = record.add_tags(['VIP Customer', 'Priority Support']) print(f"Tags Added: {add_tag_response.status}") # Add tags to multiple records at once record_ids = [4876543210000000001, 4876543210000000002] tag_names = ['Bulk Tagged', 'Campaign 2024'] bulk_tag_response = module_ins.add_tags_to_multiple_records(tag_names, record_ids) print(f"Bulk Tag Status: {bulk_tag_response.status_code}") # Remove tags from record remove_response = record.remove_tags(['Priority Support']) print(f"Tags Removed: {remove_response.status}") # Get tag count tag_id = 4876543210000000111 count_response = module_ins.get_tag_count(tag_id) print(f"Records with tag: {count_response.data.count}") # Merge tags source_tag = ZCRMTag.get_instance(tag_id=4876543210000000111) target_tag = ZCRMTag.get_instance(tag_id=4876543210000000222) merge_response = source_tag.merge(target_tag) print(f"Tags Merged: {merge_response.status}") # Delete tag tag_to_delete = ZCRMTag.get_instance(tag_id=4876543210000000333) delete_response = tag_to_delete.delete() print(f"Tag Deleted: {delete_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Manage CRM Record Attachments Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Provides methods to upload files or URLs, list existing attachments, download content, and delete attachments from records. ```python from zcrmsdk.Operations import ZCRMRecord from zcrmsdk.CLException import ZCRMException try: record = ZCRMRecord.get_instance('Contacts', 4876543210987654321) # Upload file attachment file_path = '/path/to/document.pdf' upload_response = record.upload_attachment(file_path) attachment = upload_response.data print(f"Attachment ID: {attachment.id}") print(f"File Name: {attachment.file_name}") print(f"File Size: {attachment.size}") # Upload URL as attachment link_url = 'https://example.com/shared-document.pdf' link_response = record.upload_link_as_attachment(link_url) print(f"Link Attachment ID: {link_response.data.id}") # Get all attachments for a record attachments_response = record.get_attachments(page=1, per_page=20) for att in attachments_response.data: print(f"Attachment: {att.file_name}") print(f" Type: {att.file_type}") print(f" Size: {att.size} bytes") print(f" ID: {att.id}") # Download attachment attachment_id = 4876543210000000777 download_response = record.download_attachment(attachment_id) # Save downloaded file with open(f'/downloads/{download_response.file_name}', 'wb') as f: for chunk in download_response.get_response_stream().iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded: {download_response.file_name}") # Delete attachment delete_response = record.delete_attachment(attachment_id) print(f"Delete Status: {delete_response.status}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Retrieve Deleted Records Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Fetches records from the recycle bin or permanently deleted list using the ZCRMModule instance. Requires valid module API names and pagination parameters. ```python from zcrmsdk.Operations import ZCRMModule from zcrmsdk.CLException import ZCRMException try: module_ins = ZCRMModule.get_instance('Contacts') # Get all deleted records (both recyclebin and permanently deleted) all_deleted = module_ins.get_all_deleted_records(page=1, per_page=100) print(f"Total deleted: {len(all_deleted.data)}") for record in all_deleted.data: print(f"ID: {record.id}") print(f" Type: {record.type}") print(f" Display Name: {record.display_name}") print(f" Deleted Time: {record.deleted_time}") print(f" Deleted By: {record.deleted_by.name if record.deleted_by else 'N/A'}") # Get only recyclebin records (can be restored) recyclebin = module_ins.get_recyclebin_records(page=1, per_page=100) print(f"In Recyclebin: {len(recyclebin.data)}") for record in recyclebin.data: print(f"Restorable: {record.display_name} (ID: {record.id})") # Get permanently deleted records perm_deleted = module_ins.get_permanently_deleted_records(page=1, per_page=100) print(f"Permanently Deleted: {len(perm_deleted.data)}") except ZCRMException as ex: print(f"Error: {ex.error_code} - {ex.error_message}") ``` -------------------------------- ### Generate OAuth Tokens for Zoho CRM Source: https://context7.com/zoho/zcrm-python-sdk/llms.txt Generate access tokens from grant tokens or refresh tokens for API authentication. The SDK automatically handles token persistence and refreshing. ```python from zcrmsdk.OAuthClient import ZohoOAuth from zcrmsdk.RestClient import ZCRMRestClient # Initialize SDK first ZCRMRestClient.initialize(configuration_dictionary) # Get OAuth client instance oauth_client = ZohoOAuth.get_client_instance() # Option 1: Generate tokens from grant token (one-time setup) # Get grant token from https://accounts.zoho.com/developerconsole grant_token = "1000.xxxxxxxx.xxxxxxxx" oauth_tokens = oauth_client.generate_access_token(grant_token) print(f"Access Token: {oauth_tokens.accessToken}") print(f"Refresh Token: {oauth_tokens.refreshToken}") print(f"User Email: {oauth_tokens.userEmail}") # Option 2: Generate tokens from refresh token refresh_token = "1000.xxxxxxxx.xxxxxxxx" user_identifier = "user@example.com" oauth_tokens = oauth_client.generate_access_token_from_refresh_token( refresh_token, user_identifier ) # Tokens are automatically persisted and refreshed by the SDK ``` -------------------------------- ### Set Multi-User Authentication Source: https://github.com/zoho/zcrm-python-sdk/blob/master/README.md Method to set the current user email as a thread attribute for multi-user authentication support. ```python threading.current_thread().__setattr__('current_user_email','user@email.com') ```