Zoho CRM Python SDK (V7) for different client types: Configuration and Initialization

Zoho CRM Python SDK (V7) for different client types: Configuration and Initialization


Hello everyone!

Welcome back to another week of Kaizen!

Zoho CRM Python SDK allows developers to integrate Python applications with Zoho CRM. In today's Kaizen post, we will explore how to initialize and configure the SDK for both self-clients and server-based clients.

A self-client is an application type used when you want to access your own CRM account data or set up app-to-app communication in the backend without user interaction. Self clients operate solely in the backend, making them suitable for automating tasks or data synchronization. In this scenario, the developer is both the resource owner and the client. Self-clients are ideal for scenarios such as syncing data between Zoho CRM and a legacy product management system. 

A server-based client is designed for applications that will be used by multiple Zoho CRM organizations, typically solving specific use cases for various users. These applications require both a dedicated backend server and a web UI. Server-based clients handle the authorization process and application logic, redirecting users to Zoho for authorization via a web browser. Users grant permission for the app to access their CRM data, and the application consumes this data on behalf of authorized users. This type of client is suitable for developing apps that provide specialized functionality to multiple Zoho CRM accounts, such as lead management systems or custom reporting tools.

For more information on the different client types, refer to our Kaizen post on Client Types in Zoho Developer Console.

Prerequisites

Before we go into detail about the SDK initialization process, ensure that you have the following prerequisites:
  • A Zoho CRM account and access to the Zoho API Console.
  • An IDE (e.g., PyCharm) installed in your system. In this post, we will be using PyCharm for the illustration purposes.
  • Python 3.x installed on your system or the client app.

Zoho CRM Python SDK Configuration

Configuration
Description
environment
mandatory
Specify the Zoho CRM domain and environment to make API calls to. Options include USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter, with environments like PRODUCTION(), DEVELOPER(), SANDBOX().

token
mandatory

Contains user authentication details. Used to create an OAuthToken instance with client credentials and tokens.
Supports different authentication flows:
Grant Token Flow: Uses a grant token to generate and persist access and refresh tokens.
Refresh Token Flow: Uses a refresh token to generate and persist access tokens.
Access Token Flow: Directly uses an access token for making API calls.
ID Flow : Uses the ID from the persisted token file/DB to make API calls. This method is applicable only after the SDK has been initialized at least once using a grant token, access token, or refresh token. It is not valid for the initial setup but can simplify subsequent operations by bypassing the need for other token details.
store
optional
Manages token persistence, which is the storage and retrieval of authentication tokens. Options include:
DBStore: Stores tokens in a database (e.g., MySQL).
FileStore: Stores tokens in a file.
Custom Store: Allows the implementation of custom storage logic.
If not specified, defaults to file storage in the current working directory.
logger
optional
Configures SDK logging. Allows setting log level (e.g., INFO, DEBUG, ERROR) and file path for SDK operation logs. Helps in troubleshooting and monitoring operations.
sdk_config
optional
Contains additional SDK-wide settings:
auto_refresh_fields: Enables/disables automatic refreshing of module fields. If set to true, the SDK will refresh modules and fields metadata every hour. If set to false, the metadata should be manually refreshed.
pick_list_validation: Enables/disables validation of picklist field values.
If set to true, the SDK checks user inputs against the defined picklist values. Invalid inputs, i.e., values not present in the picklist, will cause the SDK to throw an error.
 connect_timeout: Sets the maximum time to wait for connection establishment.
read_timeout: Sets the maximum time to wait for data retrieval.
resource_path
optional
Specify the directory path for storing module field information cache. 

Initializing Python SDK for Self-Clients

To initialize the SDK for a self-client:
1. Register the Client: In the Zoho API Console, create a self-client by navigating to the Self-Client section. This client is used for applications accessing only your own CRM data.

2. Generate Grant Token: After registering the client, manually generate a grant token from the API Console. Specify the necessary scopes, such as ZohoCRM.modules.ALL, based on the data you need to access.
Note: The grant token is valid for a short duration, typically 3–10 minutes, and is used to generate access and refresh tokens, using which one can access the CRM data.



3. Install the Python SDK
Install the Zoho CRM Python SDK in your Python project. The latest SDK version supports V7 of Zoho CRM APIs. 

4. Exchange Grant Token for Access and Refresh Tokens
Use the SDK in your code to exchange the grant token for access and refresh tokens. The SDK provides built-in methods to handle this process, and it will automatically manage token generation and persistence after initialization.



5. Access CRM Data:
With the tokens in place, your backend application can access and interact with Zoho CRM data programmatically, enabling tasks like data synchronization.
Here is a sample code for initializing Python SDK for a self-client.



Initializing Python SDK for Server-Based Clients

Before initializing the SDK for a server-based client, you must register your application in the Zoho API Console.


After registering the client, you can proceed with initializing the SDK for the server-based client. When using a server-based client with the Zoho CRM Python SDK, you have two options for handling authentication:
  • Generate the grant token manually and let the SDK manage the rest, including access token generation and refresh operations.
  • Write custom code to handle the entire OAuth process, from grant token generation to subsequent API calls. This approach is commonly used in server-based applications where automation and granular control over the flow are essential.
In the sample code, we demonstrate a complete implementation of initialization for a server-based client. The code includes generating the grant token for the required scopes, initializing the SDK with the tokens, and fetching records from Zoho CRM.

Understanding the Sample Code

The code defines an HTTP server that automates the OAuth process and interacts with Zoho CRM APIs. Here's a breakdown of its key functionalities:
Grant Token Generation:
When the user accesses http://127.0.0.1:8081/login, the server redirects them to Zoho's authorization page with the necessary OAuth scopes that is defined in the code.
After successful authorization, Zoho redirects the user to the redirect URL configured for the client in the API console, with a grant token and other parameters. The code parses this redirected URL to extract the grant token and the associated location.
SDK Initialization:
Using the extracted grant token, the SDK generates access and refresh tokens. These tokens are securely stored in a data store (FileStore in this case) using a unique identifier that corresponds to the user-org combination.


If no existing entry for the user-org combo is found in the token store, a new record is created with the user's grant, access, refresh tokens, and other details. When the same user logs in again, the SDK checks the token store for an existing entry. If an entry exists, the grant, access, and refresh tokens are updated while retaining the ID and user details. This ensures that no duplicate entries are created in the token store. Please note that in the background, the SDK retrieves the organization and user information to uniquely map the tokens. Without these scopes, the SDK cannot determine which user-org combination a token belongs to. Consequently, multiple entries might be created for the same user

API Call to Fetch Leads:
If the initialization is successful, the user will be redirected to http://127.0.0.1:8081/records. At this endpoint, the server uses the get_records method to fetch Leads data from the account. The response is processed, and the lead details (ID, Last Name, Company) are displayed as an HTML table.


We hope you found this post helpful and informative. By now, you should have a clear understanding of how to initialize and configure the Zoho CRM Python SDK for both self-clients and server-based clients.

Stay tuned for more insights, tutorials, and practical examples in our upcoming Kaizen posts. Your feedback matters to us. Let us know your thoughts or questions in the comments below. Until next time, happy coding!



Idea
Previous Kaizen: Kaizen #166 - Handling Query Variables in Zoho CRM | Kaizen Collection: Directory


    • Recent Topics

    • Files Uploaded to Zoho WorkDrive Not Being Indexed by Search Engines

      Hello, I have noticed that the files I upload to Zoho WorkDrive are not being indexed by search engines, including Google. I’d like to understand why this might be happening and what steps I can take to resolve it. Here are the details of my issue: File
    • Marketing Automation Emails Going to Spam

      Google is trapping all the marketing automation emails in spam. My domain has a perfect reputation and it looks like Zoho has a low reputation which is sending it to spam. When I pull the email out of spam and click on a link in the email, I get this
    • I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope.

      I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope. Here’s what I did in Postman: Generated the code to create an access token using the following URL: https://accounts.zoho.eu/oauth/v2/auth?scope=ZohoCampaigns.contact.UPDATE&client_id=<client_id>&response_type=code&access_type=offline&redirect_uri=https://1882-2-26-193-161.ngrok-free.app
    • Customer can't comment on SO or Invoice

      Hi I just saw that my customers are not able to submit a comment either on invoices or sales order. What happens if my customer hits submit is just nothing. only a red line appears on top of the page which probalby indicates an error. I'm not able to
    • Convert Request to Forum Topic

      I know you can convert a forum topic to a request and a request to a solution in the knowledge base, but how do you convert a request to a forum topic?  Is this possible?  If not is this a feature coming down the pipe in the near future? Thanks!
    • Integration of Business Hours in Email Templates

      Dear Zoho Desk Team, We would like to propose a feature enhancement to Zoho Desk that would greatly improve the utility of the Business Hours settings and streamline communication with our clients. Feature Request: Integration of Business Hours in Email
    • Send To Zoho Sign not Showing

      The button send to Zoho sign is not showing on my Zoho CRM . Is there additional steps I need to take after installing Zoho Sign to CRM ?
    • Vivaldi will not open the Zoho Mail app when I click a email link in the browser

      I'm running Vivaldi on Arch with the Plasma desktop and have under default applications Zoho Mail set as my default email client. Whenever I click a email link in Vivaldi I get the below when it should be launching Zoho. Any ideas on rectifying this issue?
    • Zoho Creator Upcoming Updates - December 2024

      Hi all, We're excited to be back with the latest updates and developments on the Creator platform. Here's what we're going over this month: Deluge AI assistance Rapid error messages in Deluge editor QR code & barcode generator Expandable RTF and multi
    • Zoho Sign / Prefill By You - Editable by Them!

      Zoho Sign seems to have two field options available - an empty field for signer(s) to complete or a field that has been prefilled by you, that becomes read only once sent.  What I would like is an option on the pre-filled by you fields, to leave them
    • How to transfer all my mails from Zoho to Gmail or Office 365

      is there any option to move my emails from zoho to gmail or office 365. i would like to export more than 25k emails from zoho to office 365 or gmail. can anyone help me to guide properly. this will help me to access my emails easily i have both account and can easily  do it with office 365 or gmail. i want two options. direct from zoho to office 365  or exported eml files from zoho to gmail. please suggest me both if possible 
    • Is the Contacts sync between Campaigns and CRM bi-directional?

      Is the Contacts sync between Campaigns and CRM bi-directional?
    • Task does not syncing to google calendar shedual

      Hi why does the tasks activities do not syncing with the google calendar like the event option does?
    • Bug with Zobot Human transfer

      I have configured the brand, the operator, and the Zobot in Spanish. However, no matter what I do, it always says "YES" instead of "Sí" or "Sure, why not " instead of "Claro, ¿por qué no?" when asking if the user wants to contact a human operator. The
    • Error AS101 when adding new email alias

      Hi, I am trying to add apple@(mydomain).com The error AS101 is shown while I try to add the alias.
    • This mobile number has been marked spam. Please contact support.

      Hi Support, Can you tell me why number was marked as spam. I have having difficult to add my number as you keep requesting i must use it. My number is +63....163 Or is Zoho company excluding Philippines from their services?
    • email address autocomplete

      Is there a way to eliminate certain addresses from showing up in auto complete when entering an address? Many old and unused addresses currently show up, many of which I would like to get rid of. Thanks
    • Something went wrong. One or more fields contain errors

      I am getting this error but there is no way to debug what field is causing the issue . I have over 100 fields. Everything was working fine and then i fixed some fields that should have the same field names but had a typo and i am getting this error. It
    • Integrating Zoho Desk Instances from two separate organizations

      Is it possible to integrate Zoho Desk with an instance from another organization? For example, creating a ticket in one organization can cause the creation of a ticket in the second organization? Or certain tickets from one organization be viewable by
    • Send Whatsapp with API including custom placeholders

      Is is possible to initiate a session on whatsapp IM channel with a template that includes params (placeholders) that are passed on the API call? This is very usefull to send a Utility message for a transactional notification including an order number
    • Knowledge base bug - Error: Article couldn't be updated.

      It took me a while to figure this out, truly one of the most irritating bugs in Zoho. I hope you find this information helpful. When using the knowledge base to create articles, make sure your keywords are in lowercase and separated by commas. Otherwise,
    • Is this possible with Campaigns?

      My company is currently moving CRM's from Monday to Zoho One. Currently, our marketing lead process is send out 7 sms messages over 14 days if the lead is in a certain status. If we don't get a response the lead is put into a "Closed" status. Do we buy
    • How to view two portals (Zoho CRM & Zoho Books) in single login

      Hello there, I need to create a portal access for the Customers. Customer data present in two applications namely Zoho CRM & Zoho Books. My requirement is to show the two different portals(Zoho CRM Portal & Zoho books Portal) in single login. I could
    • Invoice status on write-off is "Paid" - how do I change this to "Written off"

      HI guys, I want to write off a couple of outstanding invoices, but when I do this, the status of the invoices shows as "Paid". Clearly this is not the case and I need to be able to see that they are written off in the customer's history. Is there a way
    • Zoho Flow or Schedules

      I have a process where we text our leads 7 times over a 14 day with different content for each text. I created one flow in Zoho Flow to do this, but wondering if there is a more efficient way to accomplish this via Schedules. It goes on for 6 more times
    • Updating Bounced Contacts in Campaigns to the CRM

      The article explains how to update Opt-outs from Campaigns to CRM, but not bounces. While Campaigns will automatically remove any bounced emails from future campaigns, is there a process by which a bounce will update or make a notification in the CRM
    • Bandwidth, voice and poor video

      Dear Team, The webinar has made things quite easy and convenient for educators around the world. We are an art & culture-based organization where students and researchers are our major audience.  While using the Zoho webinar platform, we have observed that the audio lags and the video is of poor quality and often freezes. Some participants don't hear what is being spoken.  We also found that even a slightly slow internet connection disrupts the webinar while it should be working well even on lower
    • No Hope for Zoho Meeting

      Zoho Meeting is just the poorest meeting app I've come across in a long time. The support sucks too. I called to see if there was anything that could be done on the backend and while I was on a test meeting with support the video was lagging and freezing
    • Zoho books and venmo

      Hi, Is there a way to hook Venmo into zoho books? I have a Venmo business account and want to be able to sync that. I know you can do it with the paypal integration but I dont want to use paypal for the fees and that doesnt allow me use/integrate my current
    • Associate Email API Internal Error

      I am trying to associate an already existing email within a function using the Related Emails API. To provide more context, I also have admin permissions and have ensured that the fields are correct and that I have admin permissions when associating the
    • Contacts Don't Always Populate

      I've noticed that some contacts can easily be added to an email when I type their name. Other times, a contact doesn't appear even though I KNOW it is in my contact list. It is possible the ones I loaded from a spreadsheet are not an issue and the ones
    • 550 5.4.6 Unusual sending activity detected. Please try after sometime. <a href=https://www.zoho.com/mail/help/usage-policy.html target=_blank>Learn more.</a>

      Please help me with this. Sending of mails is blocked.
    • Segmenting Contacts Based on Product Purchased

      I am trying to organize our main Marketing Automation email list in a way that segments contacts based on products they have purchased (for example in this case it is 3 different products). To my knowledge, this would require the sync from Zoho CRM to
    • Update a lookup field in CRM from Creator using deluge

      I have a Creator form that creates a new account. When it creates the new account in the Accounts Module, I need it to also populate the Parent Account, which is a lookup field coming from the Module Parent Accounts, field Parent Account Name. I have
    • Urgent Assistance Needed with DKIM Verification

      Hi, I have been trying to verify the DKIM for the past month using your instructions as well as other resources. Unfortunately, I have not been able to resolve the issue, and it remains persistent. I need to address this problem as soon as possible so
    • Someone made ActiveSync and Autodiscover work, with iOS and macOS

      Hi, I'm trying to set this up for the fifth day now and I"m not getting anywhere. Weird thing is that somewhen in the beginning, I had it working, when I still had VirtualServers and certificates mixed up. But now it's all fine, I have the XML file from
    • How do I attach tasks from one task to other tasks in the same project

      How do I attach tasks from one task to other tasks in the same project
    • Not able to change colors help center

      Hi. How can I change the orange color in the help center? You can change everything besides this font color And how can I remove the part on the bottom?
    • Zoho Books Invoice Salesperson: requires ID but there is no "Fetch salesperson" action

      Hi, I am trying to attach a Salesperson to a Zoho Books invoice. In Zoho Flow, the salesperson field required an ID. However, I only have the salesperson name, I need to fetch salesperson by name and then provide the ID. There is no option to fetch salesperson...
    • Change format of quantity format

      Hi,  I would like to change the qunatity format from 1,00 to 1.  Is this possible?   thanks!
    • Next Page