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:



        • Recent Topics

        • screenplay

          hi, zoho rules, but it would rule even more if there was a screenplay template available - are there any plans for a creative app, perhaps with a set of theatre, television & film script templates?
        • 【Zoho CRM】日時のフィルター機能のアップデート

          ユーザーの皆さま、こんにちは。コミュニティチームの藤澤です。 今回は「Zoho CRM アップデート情報」の中から、各タブで利用可能な日時のフィルター機能のアップデートをご紹介します。 日付項目と日時項目のフィルター及びカスタムビューに、「前へ(Previous)」「次へ(Next)」の選択肢が追加されました。 ⬛︎[前へ(Previous)]:作成日時に基づきレコードをフィルターにより抽出する場合 例1. 前へ6ヶ月:当月を除く直近6ヶ月間のレコードを抽出 例2. 前へ3年:今年を除く直近3年間のレコードを抽出
        • How can I notate on check stub when a vendors credit has been applied to an invoice payment?

          I'm looking for a way of printing vendor credit memo use on a check stub when its been applied to other invoices. To let my vendors know I'm using credit memo XYZ in the amount of $xx.xx. Currently I am having to handwrite it on the stub to show my vendor
        • Multi-currency in Zoho CRM Forecast and Reports

          As a company we have branches in 4 different countries with as many different currencies. Our Sales Teams would like to work with their local currency as much as possible. The Forecast module using only 1 currency is practically usable only by the sales
        • Installment plans

          Hi I am looking for a way to allow my customer to make equal monthly payments. For instance if I create an invoice for customer Y for $1000 I want to allow them to make equal monthly payments for the next 6 months. I need those payments to be auto charged
        • Introducing Zoho CRM for Everyone: A reimagined UI, next-gen Ask Zia, timeline view, and more

          Hello Everyone, Your customers may not directly observe your processes or tools, but they can perceive the gaps, missed hand-offs, and frustration that negatively impact their experience. While it is possible to achieve a great customer experience by
        • Can i integrate bigin with google voice?

           I make all my calling through google voice to seprate my personal line from business. I want to log my calls with customers automatically but i domt see anywhere where i can do that. Any help? Im pretty sure i wont be able to. Sad
        • Zoho Books | Product updates | June 2025

          Hello Users, We’ve rolled out new features and enhancements in Zoho Books, from the option to record advances for purchase orders to dynamic lookup fields, all designed to help you stay on top of your finances with ease. Introducing Change Comparators
        • How to handle this process need using a Blueprint?

          See one minute screen recording: https://workdrive.zohoexternal.com/external/eb743d2f4cde414c715224fc557aaefeb84f12268f7f3859a7de821bcc4fbe15
        • Client Script | Update - Client Script Support For Custom Buttons

          Hello everyone! We are excited to announce one of the most requested features - Client Script support for Custom Buttons. This enhancement lets you run custom logic on button actions, giving you greater flexibility and control over your user interactions.
        • In the Blue Print Transition requirement received it will show 8 check field in pop up if they any one of this field then only move to next stage Ist quote

          In the Blue Print Transition requirement received it will show 8 check field in pop up if they any one of this field then only move to next stage Ist quote Pls help how i fix this
        • Enable History Tracking for Picklist Values Not Available

          When I create a custom picklist field in Deals, the "Enable History Tracking for Picklist Values" option is not available in the Edit Properties area of the picklist. When I create a picklist in any other Module, that option is available. Is there a specific reason why this isn't available for fields in the Deals Module?
        • The Grid is here!

          Hey Zoho Forms Community! 👋 We’re thrilled to announce the launch of a feature that’s been on your wishlist for a while: Grids What is Grids? Grids let you place form fields side by side in multiple columns to create a more concise and organized form
        • Multiselect lookup in subform

          It would be SO SO useful if subforms could support a multiselect look up field! Is this in the works??
        • AutoScan Not Working Since April -Support says it with engineering

          Hi there, Autoscan has not been working on my account since April. Without this feature, completing expenses reports is laborious and error-prone. I keep asking for updates seeing as this is a critical feature, but told that it's being looked into and
        • Is there a Waiting Room Before The Webinar Starts?

          It appears that there is no waiting room before a webinar starts. For example, with most webinar software you can collaborate with your co-presenter, set up your presentation and check to make sure everything sounds right before you go live. Zoho Meeting/Webinar
        • Optimizing Zoho CRM Integration – Tips & Insights Needed

          I hope you're all doing great! I'm currently working on integrating Zoho CRM with our platform, which helps users get iPhone Free of cost through verified government programs. Everything's coming together nicely so far, but I'd really appreciate some
        • Forms - Workflow

          Apologies if this has been asked before. I would like to know if there is a way to setup a form where a customer completes the fields/questions on Page 1 and then it is forwarded to an internal department employee who completes the fields/questions on
        • GSTIN Public Search API

          Does zohobooks have an api using which i can search GST numbers and get their details?
        • Multiple locations but one parent company

          I am trying to configure my accounts that have multiple locations under one parent company to show separate locations in the portal.   
        • Using the "Like" operator in Custom Formula

          HI there, Can someone please explain the way to use the "LIKE" operator in an IF statement to compare strings? I have tried the following but am not getting the results I'm after. if( "CurrentStatus" like 'Rejected*','Unsuccessful','Pipeline') Thanks Matt
        • Choice-based Field Rules on Global Lists

          Hi, The new Choice-based Field Rules should also be able to work with Global Lists not just local lists. Thanks Dan
        • Customer Parent Account or Sub-Customer Account

          Some of clients as they have 50 to 300 branches, they required separate account statement with outlet name and number; which means we have to open new account for each branch individually. However, the main issue is that, when they make a payment, they
        • Writing SQL Queries - After Comma Auto Suggesting Column

          When writing SQL Queries, does anyone else get super annoyed that after you type a comma and try to return to a new line it is automatically suggest a new column, so hitting return just inputs this suggested column instead of going to a new line? Anyone
        • How can I populate dropdown data with information from another source or app?

          I want to maintain a list of items in another app (say in excel or another database) and sync those as items in a drop down menu, instead of copy pasting to import. Is this kind of a feature available?
        • Mass Print Attachments from Selected Records in Custom Module

          Dear Zoho CRM Team, We’d like to request a feature enhancement regarding the handling of attachments. Use Case: We have a custom module that stores invoices uploaded by our affiliates. Currently, we need to open each record individually to print these
        • ABA Files payment description

          Hi, is there a way to automate the payment description on the ABA file creation. When you paying many vendors having to put this in each time is very time-consuming. I couldn't see if there was a way to workflow this to automate using deluge.
        • GDPR Contd. - Handling Lawful Bases for Your Customers using Zoho CRM.

          Hello folks,   Continuing from our previous GDPR post, we bring to you the first cut of GDPR centric enhancements that are released for handling lawful bases for your customers in Zoho CRM. For your understanding we have split the entire process into three sections: Identifying Data Processing Basis Updating the Data Processing Basis in Zoho CRM  Consent Management in Zoho CRM 1. Identifying Data Processing Basis The fundamental principle to handle the personal data of your data subjects is to process
        • Upgrade the Lato font to the Lato 2 font

          While there's not a major difference, I noticed that Zoho doesn't use the upgraded Lato 2 font but it instead uses the standard one. Lato 2 enhances the look of letters and numbers when you italicize them, among little things that get tweaked. Is it possible
        • Validation Rule (Date)

          Hi There,  Can any anyone help me with the validation rule? I'm trying to fire a rule whereby the End Date cannot be before Start Date.  Any takers?  Manoj Nair
        • Masked Field Type with Permission-Controlled Visibility in Zoho CRM

          Dear Zoho CRM Team, Greetings, We would like to request a new feature that would enhance data security and access control within Zoho CRM, especially when handling sensitive internal information. Use Case: Our team occasionally needs to store sensitive
        • TDS Filing

          Is there any option for automatic 26Q and 24Q filing in Zoho books. Even Tally has this option. Why don't Zoho has this ? Is there any customisation available for this ?
        • How to properly setup Databridge on Linux Server?

          Hello guys, i am running a Linux server on which I am installing the Zoho Databridge via command line. The Zoho tutorial ( https://help.zoho.com/portal/en/kb/analytics/user-guide/import-connect-to-data/databases-and-datalakes/articles/postgresql-3-3-2021#1_How_do_I_install_Zoho_Databridge
        • Running Balance in Account Statement.

          Running balance should come by default in the accounting statements but in ZOHO we need to customize every time to get the running balance in accounting statement. I did not understand, when the bank account statement opened from Bank Menu can show the
        • Haven't used banking function for years and now want to reconcile and clean up my account

          I'm in the UK and have been using Zoho Books for my private mental health practice since 2018. Up until recently, I've entered everything manually and not reconciled any items with my bank account. Every year, I run a report for that year and use that
        • invalid element hsn_or_SAC

          Hi, I am trying to record expense in Zoho expense. when submitting I am facing this issue invalid "element hsn_or_SAC" please help me with this. Regards, Abdul Hameed M
        • Configuración

          Hola acabo de instalar Zoho CRM y quiero configurarlo correctamente. Al respecto me surgen algunas dudas tales como la diferencia entre: Cuentas, posibles Clientes y Contactos. ¿Conceptualmente que son cada uno? ¿Como se se relacionan entre ellos? Si
        • Plug Sample #14: Automate Invoice Queries with SalesIQ Chatbot

          Hi everyone! We're back with a powerful plug to make your Zobot smarter and your support faster. This time, we're solving a common friction point for finance teams by giving customers quick access to their invoices. We are going to be automating invoice
        • Recap - Desk Story Series

          In our exploration of the Wheels of Ticketing Series, we kicked things off by diving into a fundamental element of Desk Ticketing: the fields. These fields serve as the building blocks that gather essential information about tickets, customers, organisations,
        • Customization of Chat Transcript Emails in Zoho SalesIQ

          Hi Zoho SalesIQ Team, I hope you're doing well. We would like to request the ability to customize the email template that is sent to clients when they request a chat transcript from SalesIQ. Currently, when a client clicks the button to receive their
        • Next Page