Python SDK

Python SDK for Zoho CRM

Python SDK for Zoho CRM APIs provides wrapper for Zoho CRM APIs. Hence invoking a Zoho CRM API from your client python application is just a method call.

Python SDK supports both single user as well as multi user authentication.

Registering a Zoho Client

Since Zoho CRM APIs are authenticated with OAuth2 standards, you should register your client app with Zoho. To register your app:

  1. Visit this page https://accounts.zoho.com/developerconsole.
  2. Click on “Add Client ID”.
  3. Enter Client Name, Client Domain and Redirect URI.
  4. Select the Client Type as "Web based".
  5. Click “Create
  6. Your Client app would have been created and displayed by now.
  7. The newly registered app's Client ID and Client Secret can be found by clicking Options → Edit.
    (Options is the three dot icon at the right corner).

Setting Up

Python SDK is installable through “pip”. Pip is a tool for dependency management in Python. The SDK expects following things from the client app

  • Client app must have Python 2.7 and above.
    • https://www.python.org/downloads/
  • Client app must have python requests being installed
    • http://docs.python-requests.org/en/master/user/install/
  • Python SDK must be installed through pip.
  • The method ZCRMRestClient.initialize() must be called on starting up of your application
  • MySQL should run in the same machine serving at the default port 3306.
    • The database name should be “zohooauth”.
    • There must be a table “oauthtokens” with the columns “user identifier”(varchar(100)), “accesstoken”(varchar(100)), “refreshtoken”(varchar(100)), “expirytime”(bigint).

If token_persistence_path is provided in oauth_configuration.properties file, then persistence happens only in the file. In this case, there is no need of MySQL.

Create a empty file with name zcrm_oauthtokens.pkl in the mentioned token_persistence_path.

Installation of SDK through pip

Install Pip(if not installed)

Please refer the document below to install pip

https://pip.pypa.io/en/stable/installing/

Install SDK

Here's how you install the Python SDK

  • Run the command below:

    pip install zcrmsdk

Python SDK will be installed and a package named 'zcrmsdk' will be created in the installation directory of python (ex. '/Library/Python/2.7/site-packages').

Upgrade the SDK

  • Run this command to upgrade the Python SDK to the latest version.

    pip install --upgrade zcrmsdk

Configurations

Before you get started with creating your php application, you need to first authenticate the app with Zoho. And to do that there are some configuration procedures that need to be in place. There are two methods in which you can authenticate your application:

  • Passing a configuration dictionary - and then call ZCRMRestClient.initialize(config);
  • Using properties files in resources folder - and then call ZCRMRestClient.initialize();

Properties file

Your OAuth Client details should be given to the SDK as a property file. In SDK, we have placed a configuration file (oauth_configuration.properties). Please place the respective values in that file. You can find that file under 'zcrmsdk/resources'.

Please fill the values for the following keys alone.

Based on your domain(EU,CN), please change the value of accounts_url. Default value set as US domain.

client_id=
client_secret=
redirect_uri=
accounts_url=https://accounts.zoho.com
token_persistence_path=

  • client_id, client_secret and redirect_uri are your OAuth client’s configurations that you get after registering your Zoho client.
  • access_type must be set to offline only because online OAuth client is not supported by the Python SDK as of now.
  • token_persistence_path is the path to store the OAuth related tokens in file. If this is set then, no need of database for persistence. Persistence happens through file only.

Include the absolute path in configuration.properties for the key “applicationLogFilePath” to store the logs. You can find that file under 'zcrmsdk/resources'. This file is to log the exceptions during the usage of Python SDK.

Please fill the value for the following key alone. If log path is not provided then logs won't be stored but you can see them in console

applicationLogFilePath=

To make API calls to sandbox account, please change the value of following key to true. By default the value is false.

sandbox=true

If your application needs only single user authentication then you have to set the user Email Id in configurations.properties file like below.

currentUserEmail=user@email.com

In order to work with multi user authentication, you need to set the user EmailId in current thread as an attribute.

threading.current_thread().__setattr__('current_user_email','user@email.com')

You can use the above one for single user authentication also but it's recommended to go with setting of email Id in configuration.properties file.

If you don't set the user email in current thread then SDK expect it from configuration.properties file. If user email is not set in any of these two then Python SDK will raise exception.

Configuration Dictionary

You can now pass the configuration values as python dictionary(key-value pair) as argument when you call the ZCRMRestClient.initialize(config) function. Below is the list of keys that are to be in the dictionary.

Mandatory FieldsOptional FieldsDatabase Fields(only when DB Persistence is used)
client_idapplicationLogFilePathmysql_username
client_secretsandboxmysql_password
redirect_uriaccess_typemysql_port
accounts_url
token_persistence_path
apiBaseUrl
apiVersion
currentUserEmail

Note:

  • If the Optional keys are not specified, their default values will be assigned automatically.

In case the "token_persistence_path" key is not provided with any value, the system automatically sets the persistence in a database, instead of a file. At that point you would have to provide additional MySQL parameters.

Below is an example of a Python dictionary containing the mandatory keys.

config = {
    "client_id":"1000.3RRCIG44JYHV040735GJGV9JA8X0YW",
    "client_secret":"29ac7e2922700ed71e37781647fa9786cf0edf7e32",
    "redirect_uri":"https://www.abc.com",
}

Below is an example of a Python dictionary containing all the keys.

config = {
    "apiBaseUrl":"https://www.zohoapis.com",
    "apiVersion":"v2",
    "currentUserEmail":"email@gmail.com",
    "sandbox":"False",
    "applicationLogFilePath":"",
    "client_id":"1000.3RRCIG44JYHV040735GJGV9JA8X0YW",
    "client_secret":"29ac7e2922700ed71e37781647fa9786cf0edf7e32",
    "redirect_uri":"https://www.abc.com",
    "accounts_url":"https://accounts.zoho.com",
    "token_persistence_path":"",
    "access_type":"online",
    "mysql_username":"",
    "mysql_password":"",
    "mysql_port":"3306"
}

Note:

  • In case "token_persistence_path" is empty and the user fails to give the mysql parameters, the dafault values will be assumed. The default value for "mysql_username" will be "root", passworkd will be left empty and the "port" will be "3306".

SQL Database Persistence

Currently, Zoho has support for only the MySQL database, in Python SDK. In case you want to use the DB persistence and you have a MySQL DB ready, you need to install the following package through "pip".

pip install mysql-connector

Once these packages are installed, you can use the mysql fields(keys) in the configuration dictionary to achieve persistence.

Initialization

The app would be ready to be initialized after defining the OAuth configuration file.

Generating self-authorized grant and refresh token

For self client apps, the self authorized grant token should be generated from the Zoho Developer Console (https://accounts.zoho.com/developerconsole)

  1. Visit https://accounts.zoho.com/developerconsole
  2. Click OptionsSelf Client of the client for which you wish to authorize.
  3. Enter one or more (comma separated) valid Zoho CRM scopes that you wish to authorize in the “Scope” field and choose the time of expiry. Provide “aaaserver.profile.READ” scope along with Zoho CRM scopes.
  4. Copy the grant token for backup.
  5. Generate refresh_token from grant token by making a POST request with the URL below

    https://accounts.zoho.com/oauth/v2/token?code={grant_token}&redirect_uri={redirect_uri}&client_id={client_id}&client_secret={client_secret}&grant_type=authorization_code

  6. Copy the refresh token for backup.

Please note that the generated grant token is valid only for the stipulated time you chose while generating it. Hence, the access and refresh tokens should be generated within that time.

Generating access token

Access token can be generated by grant token or refresh token. Following any one of the two methods is sufficient.

Generating access tokens from grant token

The following code snippet should be executed from your main class to get access token.

Please paste the generated grant token in the string literal mentioned. This is one time process only.

ZCRMRestClient.initialize()
oauth_client = ZohoOAuth.get_client_instance()
grant_token="paste_grant_token_here"
oauth_tokens = oauth_client.generate_access_token(grant_token)

Generating access tokens from refresh token

The following code snippet should be executed from your main class to get access token.

Please paste the generated refresh token in the string literal mentioned. This is one time process only.

ZCRMRestClient.initialize()
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)

Upon successful execution of the above code snippet, the generated access and refresh tokens would have been persisted through our persistence handler class.

Once the OAuth tokens have been persisted, subsequent API calls would use the persisted access and refresh tokens. The Python SDK will take care of refreshing the access token using refresh token, as and when required.

App Startup

The Python SDK requires the following line of code invoked every time your client app is started.

ZCRMRestClient.initialize()

Once the SDK has been initialized by the above line, you could use any APIs of the SDK to get proper results.

Using the SDK

Add the below line in your client app Python files, where you would like to make use of Python SDK.

import zcrmsdk

By this, you can access all the functionalities of the Python SDK.

For accessing a module or class use zcrmsdk.ClassName

Class Hierarchy

All Zoho CRM entities are modelled as modules having classes, methods and instance variables applicable to that particular entity. ZCRMRestClient is the base class of the Python SDK. ZCRMRestClient has methods to get instances of various other Zoho CRM entities. It is in RestClient module.

The class relations and hierarchy of the SDK follows the entity hierarchy inside Zoho CRM. The class hierarchy of various Zoho CRM entities are given below:

ZCRMRestClient
   -ZCRMOrganization
    -ZCRMUser
     -ZCRMUserTheme
     -ZCRMUserCustomizeInfo
    -ZCRMRole
    -ZCRMProfile
     -ZCRMPermission
     -ZCRMProfileSection
      -ZCRMProfileCategory
   -ZCRMModule
    -ZCRMLayout
     -ZCRMSection
      -ZCRMField
      -ZCRMPickListValue
      -ZCRMLookupField
     -ZCRMLeadConvertMapping
      -ZCRMLeadConvertMappingField
    -ZCRMCustomView
     -ZCRMCustomViewCategory
     -ZCRMCustomViewCriteria
    -ZCRMRelatedListProperties
    -ZCRMModuleRelatedList
    -ZCRMRecord
     -ZCRMNote
     -ZCRMAttachment
     -ZCRMInventoryLineItem
      -ZCRMTax
     -ZCRMEventParticipant
     -ZCRMPriceBookPricing
     -ZCRMModuleRelation
     -ZCRMJunctionRecord
     -ZCRMTrashRecord

As appearing in the hierarchy, every entity class will have instance variables to fetch its own properties and to fetch data of its immediate child entities through an API call.

For example, a Zoho CRM module (ZCRMModule) object will have instance variables to get a module’s properties like display name, module id, etc. and will also have instance variables to fetch all its child objects(like ZCRMLayout).

Instantiate object

It is not always effective to follow the complete class hierarchy from the top to fetch the data of an entity at some lower level, since this would involve API calls at each level. In order to handle this, every entity class will have a get_instance() method to get its own dummy object and instance variables to get dummy objects of its child entities.

Please note that the get_instance() method would not have any of its properties filled because it would not fire an API call. This would just return a dummy object that shall be only used to access the nonstatic methods of the class.

Summing it up,

  • ZCRMRestClient.get_module(“Contacts”) would return the actual Contacts module, that has all the properties of the Contacts module filled through an API call
  • ZCRMRestClient.get_module_instance(“Contacts”) would return a dummy ZCRMModule object that would refer to the Contacts module, with no properties filled, since this doesn’t make an API call.

Hence, to get records from a module, you need not to start all the way from ZCRMRestClient. Instead, you could get a ZCRMModule instance with ZCRMModule.get_instance() and then invoke its nonstatic get_records() method from the created instance. This would avoid the API call which would have been triggered to populate the ZCRMModule object.

Accessing record properties

Since record properties are dynamic across modules, we have only given the common fields like created_time, created_by, owner etc. as ZCRMRecord’s default properties. All other record properties are available as a dictionary in ZCRMRecord object.

To access the individual field values of a record, use the getter and setter methods available. The keys of the record properties dictionary are the API names of the module’s fields. API names of all fields of all modules are available under Setup → Extensions & APIs → APIs → CRM API → API Names.

To get a field value, use record.get_field_value(field_api_name). To set a field value, use record.set_field_value(field_api_name,new_value). While setting a field value, please make sure that the set value has the same data type of the field to which you are going to set it.

Response Handling

APIResponse and BulkAPIResponse are wrapper objects for Zoho CRM APIs’ responses. All API calling methods would return one of these two objects.

DownloadFile and downloadPhoto returns FileAPIResponse instead of APIResponse.

A method seeking a single entity would return APIResponse object, whereas a method seeking a list of entities would return BulkAPIResponse object.

Use the instance variable “data” to get the entity data alone from the response wrapper objects. APIResponse.data would return a single Zoho CRM entity object, while BulkAPIResponse.data would return a list of Zoho CRM entity objects.

Other than data, these response wrapper objects have the following properties:

  1. response_headers — remaining API counts for the present day/window and time elapsed for the present window reset.
  2. info — any other information, if provided by the API, in addition to the actual data.
  3. bulk_entity_response (list of EntityResponse instances) — status of individual entities in a bulk API. For example, in an insert records API may partially fail because of a few records. This dictionary gives the individual records’ creation status.

Exceptions

All unexpected behaviors like faulty API responses, SDK anomalies are handled by the Python SDK and are raised only as a single exception — ZCRMException. Hence its enough to catch this exception alone in the client app code.

Classes and it's instance variables

Module NameClass NameInstance variablesMethods
RestClientZCRMRestClient 
  • get_instance()
  • initialize()
  • get_all_modules()
  • get_module(module_api_name)
  • get_organization_instance()
  • get_module_instance(module_api_name)
  • get_record_instance(module_api_name,entity_id)
  • get_current_user()
  • get_organization_details()
OrgZCRMOrganization
  • org_id
  • alias
  • primary_zuid
  • zgid
  • primary_email
  • website
  • mobile
  • phone
  • employee_count
  • description
  • time_zone
  • iso_code
  • currency_locale
  • currency_symbol
  • street
  • state
  • city
  • country
  • zip_code
  • country_code
  • fax
  • mc_status
  • is_gapps_enabled
  • paid_expiry
  • trial_type
  • trial_expiry
  • is_paid_account
  • paid_type
  • get_instance(org_name=None,org_id=None)
  • get_user(self,user_id)
  • get_current_user()
  • get_all_users()
  • get_all_active_users()
  • get_all_deactive_users()
  • get_all_confirmed_users()
  • get_all_not_confirmed_users()
  • get_all_deleted_users()
  • get_all_active_confirmed_users()
  • get_all_admin_users()
  • get_all_active_confirmed_admin_users()
  • get_all_profiles()
  • get_profile(profile_id)
  • get_all_roles()
  • get_role(role_id)
  • create_user(user_instance)
  • update_user(user_instance)
  • delete_user(user_id)
OperationsZCRMModule
  • api_name
  • is_convertable
  • is_creatable
  • is_editable
  • is_deletable
  • web_link
  • singular_label
  • plural_label
  • modified_by
  • modified_time
  • is_viewable
  • is_api_supported
  • is_custom_module
  • is_scoring_suppored
  • id
  • module_name
  • business_card_field_limit
  • business_card_fields
  • profiles
  • display_field_name
  • display_field_id
  • related_lists
  • layouts
  • fields
  • related_list_properties
  • properties
  • per_page
  • search_layout_fields
  • default_territory_name
  • default_territory_id
  • default_custom_view_id
  • default_custom_view
  • is_global_search_supported
  • sequence_number
  • get_instance(module_apiname)
  • get_record(entityID)
  • get_records(cvid= None,sort_by=None,sort_order=None,page=0,per_page=200)
  • create_records(record_ins_list)
  • upsert_records(record_ins_list)
  • update_records(entityid_list,field_api_name,value)
  • delete_records(entityid_list)
  • get_all_deleted_records()
  • get_recyclebin_records()
  • get_permanently_ deleted_records()
  • search_records(search_word,page=0,per_page=200)
  • get_all_fields()
  • get_field(field_id)
  • get_all_layouts()
  • get_layout(layout_ id)
  • get_all_customviews()
  • get_customview(customview_id)
  • get_all_relatedlists ()
  • get_relatedlist(relatedlist_id)
  • update_module_settings()
  • update_customview(customview_instance)
ZCRMRecord
  • module_api_name
  • entity_id
  • line_items
  • lookup_label
  • owner
  • created_by
  • modified_by
  • created_time
  • modified_time
  • field_data
  • properties
  • participants
  • price_details
  • layout
  • tax_list
  • last_activity_time
  • get_instance(module_apiname,entity_id=None)
  • set_field_value(key,value)
  • get_field_value(key)
  • add_line_item(line_item)
  • get()
  • create()
  • update()
  • delete()
  • convert(potential_record=None,assign_to_user=None)
  • upload_attachment(file_path)
  • upload_link_as_attachment(link_url)
  • download_attachment(attachment_id)
  • delete_attachment(attachment_id)
  • upload_photo(file_path)
  • download_photo()
  • delete_photo()
  • add_relation(junction_record)
  • remove_relation(junction_record)
  • add_note(note_ins)
  • update_note(note_ins)
  • delete_note(note_ins)
  • get_notes(sort_by=None,sort_order=None,page=1,per_page=20)
  • get_attachments(page=1,per_page=20)
  • get_relatedlist_records(relatedlist_api_name,sort_by=None,sort_order=None,page=1,per_page=20)
ZCRMInventoryLineItem
  • product
  • id
  • list_price
  • quantity
  • description
  • total
  • discount
  • discount_percentage
  • total_after_discount
  • tax_amount
  • net_total
  • delete_flag
  • line_tax
  • get_instance(zcrm_record_instance)
ZCRMTax
  • name
  • percentage
  • value
  • get_instance(name)
ZCRMEventParticipant
  • id
  • type
  • email
  • name
  • is_invited
  • status
  • get_instance(participant_type,participant_id)
ZCRMPriceBookPricing
  • id
  • to_range
  • from_range
  • discount
  • get_instance(price_book_id)
ZCRMUser
  • id
  • name
  • signature
  • country
  • role
  • customize_info
  • city
  • name_format
  • language
  • locale
  • is_personal_account
  • default_tab_group
  • street
  • alias
  • theme
  • state
  • country_locale
  • fax
  • first_name
  • email
  • zip
  • decimal_separator
  • website
  • time_format
  • profile
  • mobile
  • last_name
  • time_zone
  • zuid
  • is_confirm
  • full_name
  • phone
  • dob
  • date_format
  • status
  • get_instance(user_id=None,name=None)
ZCRMUserCustomizeInfo
  • notes_desc
  • is_to_show_right_panel
  • is_bc_view
  • is_to_show_home
  • is_to_show_detail_view
  • unpin_recent_item
  • get_instance()
ZCRMUserTheme
  • normal_tab_font_color
  • normal_tab_background
  • selected_tab_font_color
  • selected_tab_background
  • get_instance()
ZCRMRole
  • name
  • id
  • reporting_to
  • label
  • is_admin
  • get_instance(role_id,role_name=None)
ZCRMLayout
  • id
  • name
  • created_time
  • modified_time
  • is_visible
  • modified_by
  • accessible_profiles
  • created_by
  • sections
  • status
  • convert_mapping
  • get_instance(layout_id)
ZCRMAttachment
  • id
  • parent_record
  • file_name
  • file_type
  • size
  • owner
  • created_by
  • created_time
  • modified_by
  • modified_time
  • parent_module
  • attachment_type
  • parent_name
  • parent_id
  • get_instance(parent_record,attachment_id=None)
ZCRMCustomView
  • id
  • module_api_name
  • display_value
  • is_default
  • name
  • system_name
  • sort_by
  • category
  • fields
  • favorite
  • sort_order
  • criteria_pattern
  • criteria
  • categories
  • is_off_line
  • get_instance(custom_view_id,module_apiname=None)
ZCRMCustomViewCategory
  • display_value
  • actual_value
  • get_instance()
ZCRMCustomViewCriteria
  • comparator
  • field
  • value
  • get_instance()
ZCRMField
  • api_name
  • is_custom_field
  • lookup_field
  • convert_mapping
  • is_visible
  • field_label
  • length
  • created_source
  • default_value
  • is_mandatory
  • sequence_number
  • is_read_only
  • is_unique_field
  • is_case_sensitive
  • data_type
  • is_formula_field
  • is_currency_field
  • id
  • picklist_values
  • is_auto_number
  • is_business_card_supported
  • field_layout_permissions
  • decimal_place
  • precision
  • rounding_option
  • formula_return_type
  • formula_expression
  • prefix
  • suffix
  • start_number
  • json_type
  • get_instance(api_name)
ZCRMJunctionRecord
  • id
  • api_name
  • related_data=dict()
  • get_instance(api_name,record_id)
  • set_related_data(key,value)
  • get_related_data()
ZCRMLeadConvertMapping
  • id
  • name
  • fields
  • get_instance(name ,converted_id)
ZCRMLeadConvertMappingField
  • id
  • api_name
  • field_label
  • is_required
  • get_instance(api_name,field_id)
ZCRMLookupField
  • api_name
  • display_label
  • module
  • id
  • get_instance(api_name)
ZCRMModuleRelatedList
  • api_name
  • module
  • display_label
  • is_visible
  • name
  • id
  • href
  • type
  • get_instance(api_name)
ZCRMModuleRelation
  • parent_record
  • parent_module_api_name
  • junction_record
  • api_name
  • label
  • id
  • is_visible
  • get_instance(parentmodule_apiname_or_parentrecord,related_list_apiname_or_junction_record)
  • get_records(sort_by_field=None,sort_order=None,page=1,per_page=20)
  • upload_attachment(file_path)
  • upload_link_as_attachment(link_url)
  • download_attachment(attachment_id)
  • delete_attachment(attachment_id)
  • add_relation()
  • remove_relation()
  • add_note(zcrm_note_ins)
  • update_note(zcrm_note_ins)
  • delete_note(zcrm_note_ins)
  • get_notes(sort_by,sort_order,page,per_page)
  • get_attachments(page,per_page)
ZCRMNote
  • id
  • parent_record
  • title
  • content
  • owner
  • created_by
  • created_time
  • modified_by
  • modified_time
  • attachments
  • size
  • is_voice_note
  • parent_module
  • parent_name
  • parent_id
  • get_instance(parent_record,note_id=None)
ZCRMPermission
  • id
  • name
  • display_label
  • module
  • is_enabled
  • get_instance(permission_name,permission_id)
ZCRMPickListValue
  • display_value
  • sequence_number
  • actual_value
  • maps
  • get_instance()
ZCRMProfile
  • name
  • id
  • is_default
  • created_time
  • modified_time
  • modified_by
  • description
  • created_by
  • category
  • permissions
  • sections
  • get_instance(profile_id,profile_name=None)
ZCRMProfileCategory
  • name
  • module
  • display_label
  • permission_ids
  • get_instance(profile_category_name)
ZCRMProfileSection
  • name
  • categories
  • get_instance(section_name)
ZCRMRelatedListProperties
  • sort_by
  • sort_order
  • fields
  • get_instance()
ZCRMSection
  • name
  • display_name
  • column_count
  • sequence_number
  • fields
  • get_instance(section_name)
ZCRMTrashRecord
  • id
  • type
  • display_name
  • deleted_time
  • created_by
  • deleted_by
  • get_instance(entity_type,entity_id=None)
ResponseAPIResponse
  • response_json
  • response_headers
  • status_code
  • data
  • status
  • code
  • message
  • details
 
BulkApiRepsponse
  • response_json
  • response_headers
  • status_code
  • data
  • info(ResponseInfo instance)
  • bulk_entity_response(EntityResponse instances as list)
  • status
  • code
  • message
  • details
 
EntityRepsponse
  • data
  • status
  • code
  • message
  • details
  • upsert_action
  • upsert_duplicate_field
 
RepsponseInfo
  • is_more_records
  • page
  • per_page
  • count
 
FileApiRepsponse
  • response
  • status_code
  • file_name
  • response_headers
  • status
  • code
  • message
  • details
 
CLExceptionZCRMException
  • url
  • status_code
  • error_content
  • error_message
  • error_code
  • error_details
 

Share this post : FacebookTwitter

Still can't find what you're looking for?

Write to us: support@zohocrm.com