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


    Access your files securely from anywhere


            Zoho Developer Community





                                      • Desk Community Learning Series


                                      • Digest


                                      • Functions


                                      • Meetups


                                      • Kbase


                                      • Resources


                                      • Glossary


                                      • Desk Marketplace


                                      • MVP Corner


                                      • Word of the Day


                                      • Ask the Experts



                                          Zoho Marketing Automation


                                                  Manage your brands on social media



                                                        Zoho TeamInbox Resources

                                                          Zoho DataPrep Resources



                                                            Zoho CRM Plus Resources

                                                              Zoho Books Resources


                                                                Zoho Subscriptions Resources

                                                                  Zoho Projects Resources


                                                                    Zoho Sprints Resources


                                                                      Qntrl Resources


                                                                        Zoho Creator Resources



                                                                            Zoho CRM Resources

                                                                            • CRM Community Learning Series

                                                                              CRM Community Learning Series


                                                                            • Kaizen

                                                                              Kaizen

                                                                            • Functions

                                                                              Functions

                                                                            • Meetups

                                                                              Meetups

                                                                            • Kbase

                                                                              Kbase

                                                                            • Resources

                                                                              Resources

                                                                            • Digest

                                                                              Digest

                                                                            • CRM Marketplace

                                                                              CRM Marketplace

                                                                            • MVP Corner

                                                                              MVP Corner





                                                                                Design. Discuss. Deliver.

                                                                                Create visually engaging stories with Zoho Show.

                                                                                Get Started Now


                                                                                  Zoho Show Resources


                                                                                    Zoho Writer Writer

                                                                                    Get Started. Write Away!

                                                                                    Writer is a powerful online word processor, designed for collaborative work.

                                                                                      Zoho CRM コンテンツ








                                                                                        Nederlandse Hulpbronnen


                                                                                            ご検討中の方





                                                                                                  • Recent Topics

                                                                                                  • Introducing Screening Bot for pre-screening automation

                                                                                                    We’ve transformed the chatbot experience in Zoho Recruit! What was once a general Chatbot for sourcing is now a streamlined system with dedicated tools. The original chatbot has evolved into the Sourcing Bot, while the newly introduced Screening Bot simplifies
                                                                                                  • How to Initiate WhatsApp Message on SalesIQ?

                                                                                                    I've just activated a Business WhatsApp phone number through SalesIQ because of its touted omnichannel chat approach. Sounds exciting. I understand that when a customer sends me a WA message, I can reply to it on SalesIQ and keep the chat going, perfect.
                                                                                                  • WorkDrive Download Issue

                                                                                                    My client has been sending me files via WorkDrive, which generally has worked fine. Recently files won't download at all. If you try and individually select and download a file, a popup will appear in the bottom right saying it's preparing and then it
                                                                                                  • How to get NSE/BSE Stock Prices in Zoho sheets?

                                                                                                    I've been looking for a function that provides me with the NSE/BSE listed stocks price in Zoho Sheets like GOOGLEFINANCE in Google sheets, but I found none. Please help if there is any way to het stock prices?
                                                                                                  • Downloading Image from Subform using Deluge (invokeUrl) - Data Mismatch / Connection Issues

                                                                                                    Hi Zoho Community, I'm struggling to download an image from a subform in Zoho Creator using Deluge and then attach it to a Zoho CRM Deal record. I've been working on this for a while, and I'm encountering issues that I believe are related to either data
                                                                                                  • Comment Reactions like a Thumbs Up

                                                                                                    Can we please have the ability to emoji react on comments or at the very least, thumbs a comment up? Literally every other project management system out there can support this and it is very much needed to just acknowledge a comment instead of completely
                                                                                                  • How do you send an email to a customer from Zoho Desk?

                                                                                                    I have pulled up a customer record and I click the email icon and the email address, nothing happens.... Email attached of where I am.  Is there a different way to send an email?
                                                                                                  • Feature Request – Auto-Save Draft for Interview Assessments

                                                                                                    Hello Zoho Recruit Team, I’d like to suggest a feature that would be incredibly helpful for recruiters conducting multiple interviews. Currently, when filling out an Interview Assessment, there is no option to auto-save progress as a draft. At times,
                                                                                                  • Different timezone for users

                                                                                                    Is it possible for users to set a different timezone for themselves? We have staff in different locations.   Thanks!
                                                                                                  • Attachment Template as PDF from Another Form Zoho Creator

                                                                                                    Hi Everyone, have a good day. I have question, below my script for put the attachment into email. But my template PDF from another form ("Form B"). I get errror because template PDF not exist in the form "Alasan Reject". The form name for example "Form
                                                                                                  • Reopen and Continue WhatsApp Chats within 24-Hour Window

                                                                                                    Dear Zoho SalesIQ Team, I'm writing to request a new feature that would enhance WhatsApp communication management within the 24-hour window: the ability to reopen and continue conversations with customers after a chat has been closed from our end. Current
                                                                                                  • Accessing Extension Created Functions

                                                                                                    Good day. I have recently been attempting to access a function from an extension that is installed on my crm in a standalone function I have created with deluge on Zoho CRM, however I have not managed to get this to work. I am attempting to send an SMS
                                                                                                  • Unchecked an option in a checkbox when another option is checked

                                                                                                    Hi, in a Creator form, I have around twenty checkbox fields, named for example "cb1", "cb2", "cb3", etc... Each of these fields have two options: Done and N/A. I would like to be able to for each field, if I check "Done", "N/A" is unchecked, and if I
                                                                                                  • Ability to Initiate WhatsApp Template Messages in Zoho SalesIQ Without Preexisting Chat

                                                                                                    Hi Zoho SalesIQ Team, I hope you're doing well. I understand that with the WhatsApp integration in SalesIQ, clients can contact us via WhatsApp, and we can use WhatsApp templates to send messages outside of the 24-hour window by reopening an existing
                                                                                                  • Support streaming display of long texts in zobot chats (usefull for chatgpt / openAI and any other AI )

                                                                                                    Hello, I was able to test the new features you offer to connect chatgpt or openAI assistant with built-in feature or custom code. This is great but the chat seems very slow and laggy because you don't use streaming api from openAI, so the chat has to
                                                                                                  • Is it possible to load a Module with a filter pre-applied by the URL?

                                                                                                    In many of the CRM related lists, there is limited sorting, and no filtering available. I thought of the idea of putting a Custom Button on a Related List that would take the user to that module, but PRE-FILTERED by the Account from where they were viewing
                                                                                                  • Custom Icon on zoho Creator APP

                                                                                                    Is is possible to have a company logo as the APP image rather than the Zoho image?  thank you.
                                                                                                  • How can I format numbers in an html table?

                                                                                                    I am building an html table to display how much people have paid, but the numbers are losing their formatting: application_table = application_table + "<td style='text-align: right;'>" + payment_row.Amount_Local + "</td>"; Amount_Local is a decimal field,
                                                                                                  • Weekly Tips: Stay on Top of Work with Zoho Mail Streams

                                                                                                    You’re working on a big project, and all the updates from your team keep coming in from different angles. Some are sharing updates, others are asking questions, and you are constantly getting your inbox piled up with new information on the same project.
                                                                                                  • Issue with Zoho Books /Zoho Inventory Support Team

                                                                                                    Oh my goss! This ticket just got closed without a solution/response?! (attached screenshot) That is so pathetic. I thought I could keep impartially all tickets tracked in your help website. Do I need to track issues raised to zoho support team in a separate
                                                                                                  • Stock Count - Extracting Data

                                                                                                    Hi, I really like the new stock counting functionality however I can't find any way to extract the stock count results. -The build in stock count report is limited and has no export option - There is no export options from within the stock count screens
                                                                                                  • Issue with Bin Locations and Stock Counting in Zoho Inventory

                                                                                                    Dear Zoho Support, We are currently experiencing a significant issue with bin locations and stock counting in our warehouse. Our warehouse is divided into 7 zones, each containing approximately 250 bin locations. When performing a stock count for an item,
                                                                                                  • PO receive limitations

                                                                                                    It is VERY common to receive more or less that the PO quantity. It's totally ludicrous to limit the maximum receive to the PO quantity! What if the receive is 0.00001 less than the PO quantity - it leaves the PO as "Partially received" The current options are to edit the PO manually before finalizing the receive, an outrageous situation ! Please Zoho guys - this is an infuriating oversight & can be easily resolved by introducing the option as shown in the attached document ......
                                                                                                  • Boost Customer Experience: Let Visitors Choose Their Preferred IM Channel in Your Chat Widget

                                                                                                    We have an exciting enhancement coming your way. Pushing the perimeter has always been our thing, and we have come up with yet another enhancement for your Zoho SalesIQ live chat. Did you know your live chat can support more than chats and calls? That's
                                                                                                  • Ask the Experts 17: Elevate Customer Communication With Multichannel & Instant Messaging

                                                                                                    Hello Everyone, Get ready for the opportunity to interact with Zoho Desk specialists! This month, we’re diving into Multichannel Operations, helping you manage customer interactions across various platforms seamlessly. Why Join? Customers reach out through
                                                                                                  • Auto Reply on Zoho Desk

                                                                                                    Can we set an Auto Respond to every email that Zoho Desk receives? Is there a way that any of the information in the original email can be pulled through to that reply? Like a mail merge?
                                                                                                  • Several issues with formatting within the email campaign

                                                                                                    I continue to have several issues with formatting when creating newsletter through this platform. Any one have any guidance on how to deal with these issues? The newsletter content always gets clipped when first opened. To see the content in its entirety, you have to scroll all the way to the bottom and click a button to open it all up. Is there a way to make all content appear without having to click to open it up? I'm sure many people don't realize this and therefore don't see the content that
                                                                                                  • Blueprint Issue - Being able to set a subform field as mandatory

                                                                                                    I'm creating a blueprint. My record involves a subform which is only shown once field is set but the field gets set in step two of the process. My problem - I can't save the record as the subform field is set to mandatory - If I unset the mandatory field,
                                                                                                  • Zoho connect manuals and workflows

                                                                                                    Is there any plans to allow workflows to be triggered from changes or edits to a manual? It would get us over the line for deployment if there was.
                                                                                                  • Customer Portal Users Metrics

                                                                                                    Hi, Is there any way to know who and when a specific customer portal user accessed? without having to use the metrics page.
                                                                                                  • Notebook stacks

                                                                                                    Hello, Are you planning to implement some kind of notebook grouping, similar to evernote stacks? I know that we can group notes inside of the particular notebook but for a lot of us it is not enough I belive. Sometimes that additional layer for organization
                                                                                                  • Multi Step Parallel Transitions for Blueprints

                                                                                                    We have two processes, that are sequential and can be done simultaneously inside of one module. For example: For order processing, we have to kinds of tasks: tasks that need to be done at the car directly (for example repairs) and tasks where the physical
                                                                                                  • Accessing Attachments in Zoho Recruit Extension for API Integration

                                                                                                    Hi, I am currently developing a Zoho Recruit extension to integrate with a third-party application. As part of this, I need to retrieve the attachment file from the current record and include it in an API request. However, I couldn’t find a relevant Zoho
                                                                                                  • CRM - QR Codes and Bar Codes

                                                                                                    Hi I am using CRM to run my service team - Asset maintenance business We need to move to and generate a QR code for each Asset we look after. And we need Bar code reading for the testing we do. (pre-bar-coded sample bottles are provided by the lab) Does
                                                                                                  • Mails to Deals

                                                                                                    Hi everybody. We are using ZOHO CRM connected to ZOHO Mail and we have a big trouble, which our ZOHO partner is not able to solve. Zoho CRM automatically connects received emails to last edited live Deal of the same Contact. For us this logic is very
                                                                                                  • How to check if the sum of number fields match 100%

                                                                                                    I have 12 fields (12 months) which contain a number. When I sum the fields in a formula field I see the total, but I want to be sure that the total is always 100 (%). How do I validate that, since you can't validate an formula field it seems.
                                                                                                  • How to Send Weekly Scheduled Emails of a Custom View

                                                                                                    Greetings, We have a custom view called "All Employee View" for the Employee form. We are able to manually export that view using the "Export" button: However, we want to programmatically export this view as an XLS file each week and send it in an email
                                                                                                  • Introducing our latest privacy enhancement - Hiding email IDs in Zoho Cliq Networks

                                                                                                    Hello everyone, Zoho Cliq Networks offers a powerful collaboration platform that allows businesses to create dedicated digital workspaces for external vendors, partners, or individuals you want to communicate with professionally without adding them to
                                                                                                  • The amount entered is more than the balance due for the selected bills."

                                                                                                    Hi Team i am trying to record payments for vendors using API and getting this error in response as { "code": 28011, "message": "The amount entered is more than the balance due for the selected bills." } JSON is prepared according to Documentation and
                                                                                                  • Can I print a set of record templates as a single pdf?

                                                                                                    I have a record template formatted as a gift certificate. I can email a single gift certificate to each recipient, but I also need to print the whole batch for the organiser, and they won't want 40 separate files. The layout needs to be identical, so
                                                                                                  • Next Page