Kaizen 191: Implementing Login with Zoho using Python SDK

Kaizen 191: Implementing Login with Zoho using Python SDK

      
Welcome back to another week of Kaizen!!

This week, we are diving into how to implement secure user authentication using Login with Zoho and integrate it with Zoho CRM through our Python SDK.

To ground this in a real-world scenario, we will look at how Zylker Academy, a training institute offering web design and development courses, uses an internal portal that connects directly to Zoho CRM. This setup allows course coordinators to manage student data without maintaining a separate backend database.

Zylker receives frequent student enquiries and uses Zoho CRM to manage all related information. Every course coordinator, academic advisor, and support staff member who needs access to student information is added as a user in Zoho CRM, with access permissions aligned to their role. Instead of using Zoho’s interface directly, Zylker’s team works through a custom internal web portal, tailored to their workflow. This portal connects directly to Zoho CRM, reading from and writing to it, but does not have its own database.

But before this portal can access any CRM data, it must authenticate itself securely. Every time a user opens the portal, they must log in with their Zoho account. Once authenticated, they will be granted access to the CRM modules and records they are authorized to work with. That is where Login with Zoho comes in.

What is "Login with Zoho"?

Login with Zoho is Zoho’s implementation of the OAuth 2.0 Authorization Code flow. It allows applications to authenticate users and access their Zoho CRM data without ever handling their passwords.
Instead of asking users for their Zoho credentials directly, the app redirects them to Zoho’s login screen. Here is how it works:
  1. The app redirects the user to Zoho’s login page.
  2. The user logs in and approves the requested permissions (scopes).
  3. Zoho sends back an authorization code.
  4. The backend exchanges this code for access and refresh tokens.
  5. These tokens are used to make authenticated API calls.
This flow ensures that users maintain full control over their data. They can revoke access at any time, and your application never handles or stores passwords. 
In Zylker’s case, every time a coordinator opens the portal, they are prompted to log in with their Zoho account. Once authenticated, they can immediately begin working with student records—all backed by Zoho CRM.

Use Case Implementation: Zylker’s Student Management Portal

To demonstrate how this login flow works, we have built a stripped-down version of Zylker's portal:
  • A front-end form to enter and view student data
  • A backend server that interacts with Zoho CRM via the Zoho CRM Python SDK
The application includes a simple form for capturing student details—name, college, course, email, and phone number. Submitted data is treated as a Lead in Zoho CRM.
The app allows users to:
  • Add new leads
  • View a list of all registered leads
  • Edit an existing lead’s information
  • Delete records if necessary
All actions go straight to Zoho CRM using its Python SDK. But before any of this can happen, the user must complete the login flow.

Sample Project Structure

Before going into the implementation details, let us briefly define the components of the project.

Frontend
The frontend is a simple static web interface built with HTML, CSS, and JavaScript. It runs in the browser and handles user interactions and triggers backend API calls. These are the main files:
  • index.html : Main UI for login, data entry, and record viewing.
  • script.js : Contains the client-side logic to trigger login, submit data, and render records.
  • redirect.html :  A minimal page used to capture the authorization code returned by Zoho after login.
The frontend is served using any static server (e.g., Live Server in VS Code) and runs on http://localhost:5501/ in our example. 
Download the files from here.
Configuration Notes:
  • In script.js, update the redirect_url value in the login request to match your actual domain or port if you’re not using localhost:5501.
  • Ensure the URL in the Zoho API Console matches this redirect URI and port.
Backend
The backend is a Python server that handles all interactions with Zoho CRM via the Python SDK. It includes:
  • server.py : A custom HTTP server that:
    • Generates the Zoho login URL
    • Exchanges the authorization code for tokens
    • Initializes the SDK
    • Exposes endpoints like /create, /get_records, /update, and /delete
  • record.py : Contains functions to create, fetch, update, and delete records in CRM modules like Leads. Each function uses the Zoho Python SDK methods to perform a specific operation.
This server runs on http://127.0.0.1:8085/ in our example. 

Download the files from here.
Configuration Notes:
  • In server.py, replace the client_id with your actual client ID from Zoho's API Console.
  • In record.py, replace the client_secret with your actual client secret.
  • If required, change the front-end server’s host and port in the run() function at the bottom of server.py:
    def run(server_class=HTTPServer, handler_class=SDKInitialize, port=xxxx):

Sample project flow

      

Step 1: Register the application with Zoho API console

To initiate the login process, you need to register your application on the Zoho API Console. This is a one-time setup that provides your app with a Client ID and Client Secret, both of which are required to authenticate users and exchange authorization codes for tokens.
To register your application:
We will be using these values in the backend script (server.py)  that handles token exchange.

NotesNOTE: To support users from multiple data centres, make sure to enable multi-DC support for your application. You can do this by going to your app’s settings in the Zoho API Console and turning on the Multi-DC option.

Step 2: Implementing the login flow

Here is a walkthrough of the flow implemented in the project:

1. Page loads and triggers login

When a user opens the portal, the frontend automatically initiates the login sequence. It first makes a call to the backend to retrieve the Zoho authorization URL. 

In index.html, this triggers getRecords() on page load:
  1. <body onload="getRecords();">
In script.js, getRecords() calls the login() function:
  1. async function getRecords() {
  2.     login();
  3. }
The login() function sends a request to the backend to get the Zoho OAuth authorization URL.

2. Backend builds login URL

The backend responds with an OAuth URL that includes:
  • Your client ID
  • Scopes like ZohoCRM.modules.ALL
  • The redirect URI
In server.py, under do_GET, the /login endpoint generates the OAuth URL:
  1.    if parsed_url.path == '/login':
  2.             redirect_url = query_params.get('redirect_url', [''])[0]
  3.             scope = "ZohoCRM.settings.fields.ALL,ZohoCRM.modules.ALL,ZohoCRM.users.READ,ZohoCRM.org.READ"
  4.             url = "https://accounts.zoho.com/oauth/v2/auth?scope=" + scope + "&client_id=" + self.client_id + \
  5.                   "&redirect_uri=" + redirect_url + "&response_type=code&access_type=offline"
  6.             self._set_headers()
  7.             # Send response
  8.             response = {"url": url, "redirect_url": redirect_url}
  9.  self.wfile.write(json.dumps(response).encode('utf-8'))
Once the frontend (script.js) receives the login URL, it opens it in a popup window.
  1. const response = await fetch('http://127.0.0.1:8085/login?redirect_url=http://127.0.0.1:5501/redirect.html');
  2. const data = await response.json();
  3. const popup = openCenteredPopup(data.url, "PopupWindow", 600, 400);
Here's an example of the Zoho OAuth authorization URL format:
      scope=ZohoCRM.modules.ALL&
      client_id=YOUR_CLIENT_ID&
      response_type=code&
      access_type=offline&
      redirect_uri=YOUR_REDIRECT_URI

3. User logs in on Zoho

The user logs in with their Zoho credentials and is prompted to approve the app's access. Once they approve, Zoho redirects them to the specified redirect URI along with an authorization code and location parameter. The location parameter indicates which data centre the user belongs to.

4. Frontend captures the authorization code

The redirect page, a minimal HTML file (redirect.html),  reads the URL parameters and stores them in localStorage, then closes the popup:
  1. function setAccessToken() {
  2.     var hashProps = getPropertiesFromURL();
  3.     if (hashProps) {
  4.         for (var key in hashProps) {
  5.             if (hashProps.hasOwnProperty(key)) {
  6.                 localStorage.setItem(key, hashProps[key]);
  7.             }
  8.         }
  9.     }
  10.     setTimeout(function () { window.close(); }, 0);
  11. }

5. Token exchange and SDK initialization

Once the popup window is closed, the main window retrieves the authorization code and location and sends them to the backend’s /initialize endpoint.
In script.js:
  1. var code = localStorage.getItem("code");
  2. var location = localStorage.getItem("location");
  3. initialize(code, location, data.redirect_url);
  4. .
  5. .
  6. async function initialize(code, location, redirect_url) {
  7.     const response = await fetch('http://127.0.0.1:8085/initialize?code=' + code + '&location=' + location + '&redirect_url=' + redirect_url);
  8. }
In server.py, the /initialize endpoint handles SDK initialization:
  1. elif parsed_url.path == '/initialize':
  2.     code = query_params.get('code', [''])[0]
  3.     location = query_params.get('location', [''])[0]
  4.     redirect_url = query_params.get('redirect_url', [''])[0]
  5.     LeadsRecords().init(self.client_id, code, location, redirect_url)
In record.py, the SDK is initialized and tokens are stored.
  1. token = OAuthToken(client_id=client_id,
  2.                    client_secret=client_secret,
  3.                    grant_token=code,
  4.                    redirect_url=redirect_url)
  5. Initializer.initialize(environment=environment,
  6.                        token=token,
  7.                        logger=logger,
  8.                        store=store)  # FilePersistence or custom store
This exchanges the authorization code for:
  • An access token (valid for one hour)
  • A refresh token (used to get new access tokens)
These tokens are saved in a local file (sdk_tokens.json). This is configured using Zoho’s FilePersistence class during SDK initialization 

How are tokens linked to users?

The SDK maps each access and refresh token pair to a unique user-organization combination. This means tokens generated for different organizations by the same user are stored separately. Likewise, if a user generates new tokens for the same organization, the SDK updates the existing tokens instead of creating duplicates. This ensures that API calls always use the correct tokens tied to the authenticated user and their organization. 

To enable this mapping, the SDK retrieves the user and organization information in the background. This requires the appropriate scopes to be included during authentication, ZohoCRM.users.READ and ZohoCRM.org.READ. Without these scopes, the SDK cannot identify the user-org combination correctly, which can lead to multiple token entries for the same user. That is why, in our sample project, we have included these scopes explicitly in the server.py file during the SDK initialization.

Once the SDK is initialized, the user is logged in, and the app can begin making CRM API calls on their behalf.


Step 3: Accessing Zoho CRM

Once the user is authenticated and the Zoho SDK is initialized on the backend, the frontend can call custom backend endpoints like /create or /get_records. These endpoints use the authenticated SDK instance to make CRM API calls on behalf of the user.
  • GET /get_records?module=Leads : View all students
  • POST /create?module=Leads : Add new student
  • PUT /update?module=Leads&id=... : Edit existing entry
  • DELETE /delete?module=Leads&id=... : Remove existing entry

Deploying the sample project

To run this application, you will need two components:
  1. A frontend server to serve your HTML files (index.html, script.js, redirect.html). This can be done using any static web server (e.g., Live Server in VS Code).
  2. A Python backend server that handles login, token storage, and CRM API communication. You can run it using:
    python server.py
In the given example, both servers communicate over localhost. You should set your redirect URI accordingly when registering your app in the Zoho console.

Conclusion

Login with Zoho is a secure, OAuth-based mechanism that allows users to authorize your application to access their Zoho CRM data. In this example, we built a real-world use case, a student portal for Zylker Academy, that authenticates users and interacts with CRM directly using the Zoho CRM Python SDK.
By walking through the entire flow, you now understand:
  • Why OAuth is essential for secure CRM access
  • How to register an application in Zoho
  • What the login and token exchange flow looks like
  • How to implement "Login with Zoho" in your applications

What is next?

In this project, we have used a simple file persistence method to store the token files. But in a real world scenario, this may not always meet your business requirements. In next week's Kaizen, we will implement custom token persistence instead of file persistence in the current project. We will explain how to implement this using SQLite, In-Memory and List DBs. With that, you will be equipped to implement a persistence method that fits your application architecture and deployment environment.

We hope that you found this useful. If you have any queries, let us know the comments below, or send an email to support@zohocrm.com. As always, we would love to hear from you!!

Stay tuned for next week's Kaizen : Implementing Custom Token Persistence 


Download Links:
Further Reading:


      • Sticky Posts

      • Kaizen #198: Using Client Script for Custom Validation in Blueprint

        Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Kaizen #197: Frequently Asked Questions on GraphQL APIs

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

        Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
      • Kaizen #193: Creating different fields in Zoho CRM through API

        🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Client Script | Update - Introducing Commands in Client Script!

        Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands

        • Recent Topics

        • Related Lists filter

          I have Contacts showing in our Accounts module. I customized the Contacts module with an Employment Status field, with the following picklist options: "Primary Contact", "Secondary Contact", "Active Staff(not a main contact)", and "No longer employed".
        • Automation Assistance for Zoho Form Integration and Workflow

          Hi, We are currently using a Zoho Form to send out our Global Credit Application and would like to automate the process further. Specifically, we’d like the ABN number submitted through the form to automatically populate the GST/VAT Number field in Zoho
        • Is it possible to Bulk Update 'Product Name' in Zoho Desk?

          Is it possible to Bulk Update 'Product Name' in Zoho Desk? I cannot see that option now. Kindly help how we can do it.
        • Adding Overlays to Live Stream

          Hello folks, The company I work for will host an online event through Zoho Webinar. I want to add an overlay (an image) at the bottom of the screen with all the sponsors' logos. Is it possible to add an image as an overlay during the live stream? If so,
        • Zoho arrives to Spam on all Microsoft Accounts (Outlook, Hotmail, Microsoft 365)

          I believe this is a very serious issue. All my email accounts in Zoho arrives straight to SPAM. Thing is, a lot of clients rely on email arriving to Inbox, specially on Microsoft Accounts since it is used a lot both for business and personal email sending.
        • Campaign Links Blocked as Phishing- Help!

          We sent a Campaign out yesterday. We tested all of the links beforehand. One of the links is to our own website. After the fact, when we open up the Campaign in our browser, the links work fine. The links in the emails received, however, opened in a new
        • ADDDATE formula using 2 calculations

          Hello, I want to create an ADDDATE formula using 2 calculations, add 1 month and deduct 1 day. the formula that I need should look like this: ADDDATE(due_date, 1, "Months")+ ADDDATE(due_date, -1, "Days") Each row itself works fine, but when I'm trying
        • Best way to handle a credit card download fiasco

          Hi there, hoping that someone knowledgable with book keeping can give me the answer here. One of my credit cards has been integrated with Zoho books and we have been downloading transactions with no issue. The credit card got compromised and was used
        • Making money out of Zoho Sheets - How?

          Hello, Suppose I come up with a brilliant Zoho Sheet that I want to sell to other people, can I do this? How? Thanks.
        • How Do I Refund a Customer Directly to Their Credit Card?

          Hi, I use books to auto-charge my customers credit card. But when I create a credit note there doesn't seem to be a way to directly refund the amount back to their credit card. Is the only way to refund a credit note by doing it "offline" - or manually-
        • is it possible to add more than one Whatsapp Phone Number to be integrated to Zoho CRM?

          so I have successfully added one Whatsapp number like this from this User Interface it seems I can't add a new Whatsapp Number. I need to add a new Whatsapp Number so I can control the lead assignment if a chat sent to Whatsapp Phone Number 1 then assign
        • Specify in-line image size in question

          I have an image inserted into a file upload type question. I can click and drag the corner of the image to make it larger or smaller, but I would like to manually input the dimensions I need. No matter what size I make the image in photoshop before uploading
        • On click of the Blueprint transition (Qualified or Not Qualified), the 'Convert' option should be enabled in the Lead module.

          On click of the Blueprint transition (Qualified or Not Qualified), the 'Convert' option should be enabled in the Lead module. console.clear(); let convertButton = ZDK.Page.getButton('convert'); let leadStatus = ZDK.Page.getField('Lead_Stage').getValue();
        • Mobile Display Issues on Zoho Sites After Recent Update

          Hello! I’m currently facing an issue with my Zoho website that I created for my small business. After the recent updates, I’ve noticed that my site is not displaying correctly on mobile devices. Specifically, the layout appears distorted, and some elements
        • View Linked Subscription on Invoice list

          When looking at the list of invoices in billing is it possible to see the subscription that an invoice is for. This would allow you to see if it's a subscription a customer is behind on, or they simply haven't paid a one time invoice.
        • Can i set per-client hourly rate in Zoho Desk and not to correct the calculation on invoice?

          We use Zoho Desk to run one ticket per client per month. All time entries go to the ticket, we have to enter hourly rate manually and then correct it when we do the invoicing at the end of the month. So, our workflow is as following: I worked for 30 minutes,
        • Zoho Desk + Jira integration - Email notifications and comments posted by administrator instead of real user

          Dear All, I set up the integration under my admin account, and now when users leave comments in Jira (to created tickets in Zoho Desk), the email notifications show that the ‘Administrator’ left a comment, not a real user. The same happens in the ticket
        • Unable to add Agents

          I am trying to add agents to my account. While filling the details and sending invitation, the system mentions that invitation is sent. But no email is received on the user side. I have tried this multiple times and have also checked Spam and other
        • Auto CC - Moving Departments

          We have Auto CC e-mail replies to your support mailbox enabled. We have two departments: Helpdesk (helpdesk@domain.com) Delivery (delivery@domain.com) If we create a Helpdesk ticket, and reply, replies are CC'd to helpdesk@domain.com (OK) We then move
        • How to add new widgets?

          Searched and searched and cannot find anywhere. Why is everything so hidden in zoho! Why is there not a button right here that allows me to create a new one, why is it buried somewhere else! Zoho's UI is so infuriating
        • Client Script also planned for Zoho Desk?

          Hello there, I modified something in Zoho CRM the other day and was amazed at the possibilities offered by the "Client Script" feature in conjunction with the ZDK. You can lock any fields on the screen, edit them, you can react to various events (field
        • Submit Ticket from Custom Form on Website

          Hi I would like to create new tickets from our custom form on our website including some custom fields like serial number. I would prefer PHP to create the ticket. I know there is the Zoho webform but we would like to create our own. I have now read into the API and with AuthToken this would work with PHP but it is deprecated  and will not be supported any more in the future, so this not an option. OauthToken on the other hand needs an interaction from the ticket creator (customer) which we would
        • I can't found API for Sales Receipts

          Hello May you please help me to find an API document for Sales Receipts to get data and retrive a custom fields like Invoice and credit notes Regards
        • Customising Sign Up Page in Zoho Help Centre Sandbox

          Hi, I would like to customise the Sign Up page in my Help Centre Sandbox Environment but when I try to access it I get this message: What setting or permission do I need to achieve this? Many thanks, Kunal
        • Workdrive on Android - Gallery Photo Backups

          Hello, Is there any way of backing up the photos on my android phone directly to a specific folder on Workdrive? Assuming i have the workdrive app installed on the phone in question. Emma
        • Sort data in Pivot Table

          Is it possible to sort by a data field. I can gruop and filter, but I culdn't find how to sort the results. Tank You.
        • How to interact webhooks with Creator?

          How can I interact webhooks from external websites with Zoho Creator?  I'd like to get notifications from external websites (Stripe, Zoho Subscription, etc.) These notifications are coming as HTTP POST request from those servers, on maybe daily, monthly or based on any events.  How should I prepare my app in creator to receive these requests? Where and how to should I program in Deluge if I'd like to add some part of the JSON/XML data to my form?  Thank you BR, Balazs
        • No Experiment Visitors

          I have an experiment running for five days. PageSense web analytics data shows the page is getting visitors, but the experiment data itself says zero visitors. I am in trial mode, not sure if that's related. A week ago, I contacted support through chat
        • Detailed General Ledger has problem of exporting out to excel and missing ledger details for some accounts

          I have been encountering some problems generating Detailed General Ledger report with Zoho books. Firstly, I cannot export out the report of Detailed General Ledger to Excel. It will show this error message "invalid value passed for sort column", and
        • How do I get at the data in "Partially Saved Entries"?

          Hi, Zoho Newbie here - I'm helping to support an existing Zoho installation, so this is all a bit new to me. I have to say, I'm liking what I've seen so far! We've just spotted that we have a number of respondents to our forms who don't end up submitting
        • SOLVED: Stopping Multiple Invitations when sync with Google Calendar

          I wanted to share this solution as I wasn't able to find it when searching through the Zoho community and via web search. The issue: When requestor books a meeting through Zoho Bookings, the requestor receives a confirmation email from both Bookings and
        • Help Needed with Creating Close % Reporting

          Now that our company has a good data set to work with we want to use ZCRM reports ways to track the performance metrics we have established. Specifically, I want to be able to calculate closing % for individual salespeople and individual support people.
        • Empowered Custom Views: Cross-Module Criteria Now Supported in Zoho CRM

          Hello everyone, We’re excited to introduce cross-module criteria support in custom views! Custom views provide personalized perspectives on your data and that you can save for future use. You can share these views with all users or specific individuals
        • Restricting Calendar View to Working Hours

          Hi: I'm trying to implement a calendar which displays all of my customer appointments.  Currently, the calendar shows all 24 hours of the day.  Is there a way to restrict the hours to simply the times my business is open? Thanks!
        • Color of Text Box Changes

          Sometimes I find the color of text boxes changed to a different color. This seems to happen when I reopen the same slide deck later. In the image that I am attaching, you see that the colors of the whole "virus," the "irology" part of "virology," and
        • Static Prefill URLs Functionality in the App

          Hi, It would be great to be able to use the same functionality within the App, so create the Static Prefill URL as today and be able to use online as today, and then have an area within the App showing these Entries that can be pressed and opens the form
        • Residual Formatting in Text Boxes After Undoing Pasting of Formatted Text

          Hi, guys! I have another problem to report. Actually, I have been aware of this for many months, possibly years, but I have been too lazy to report it to you. My apologies! Let's say you've pasted a formatted string into a text box. You change your mind
        • Tabular View Report | Scale To Fit Screen

          Please add the option to scale Tabular View reports to fit the screen. I constantly have to adjust the column size of Tabular View reports to fit various screen sizes and it just looks messy. You can see in the screenshot below there is a blank gap after
        • Adding a work order for Assets vs. changing the contact person

          When adding a work order for an existing Assets (e.g. service), the assigned contact cannot be changed (deleting the contact deletes the selected Assets). This results in such an illogical operation that if you want to change the person to be contacted,
        • Zoho Projects - Q2 Updates | 2025

          Hello Users, With this year's second quarter behind us, Zoho Projects is marching towards expanding its usability with a user-centered, more collaborative, customizable, and automated attribute. But before we chart out plans for what’s next, it’s worth
        • Next Page