Kaizen 235 - Restore deleted records from the Recycle Bin using Zoho CRM APIs

Kaizen 235 - Restore deleted records from the Recycle Bin using Zoho CRM APIs


Welcome to another Kaizen week.

Here's a question that came up in our developer forum:

"I'm working on a piece of software to automate conversion of Leads into Deals based on order status from my company's website. There are some cases where a previously deleted Deal needs to be restored, such as when a failed order is manually corrected. Recovering a record from the recycle bin manually is trivial, but obviously I'm trying to automate the whole process. Is it possible to recover a record from the recycle bin using the API?"

This is a problem that many developers may have run into when building integrations.

Consider Zylker, a company that syncs orders from their e-commerce platform directly into Zoho CRM as Deals. Their workflow is straightforward: a new order comes in, a Deal is created. An order fails, the Deal gets deleted. Clean and simple.

But real-world workflows rarely stay that simple. Sometimes a failed order gets manually corrected on the e-commerce side. The customer fixes their payment, the warehouse confirms stock, the ops team overrides the rejection. When that happens, Zylker needs to bring that Deal back to life in CRM, complete with all its history, notes, activities, and associations.

The naive solution is to create a new Deal. But that means losing everything that was attached to the original record like call logs, emails, notes, contact role associations. For a sales team, that history is valuable. Creating a duplicate isn't a restore, it's a data integrity problem waiting to happen.

The right solution is to restore the original Deal from the Recycle Bin programmatically. This is the problem we’ll address in this post.

 What the Recycle Bin API offers 

To implement this workflow, we’ll rely on the Recycle Bin APIs available in Zoho CRM.  There are six key endpoints:

 1. Get Recycle Bin records 

Endpoint: GET {api-domain}/crm/v8/settings/recycle_bin

This endpoint fetches all deleted records across modules. In Zylker's case, this is how we search for a deleted Deal before restoring it. The API supports a filters parameter to narrow results based on module, display name, deletion time, or user.

Other supported parameters are:

  • ids - retrieve specific records by their unique IDs. Takes precedence over filters if both are provided

  • sort_by - sort by display_name, deleted_time (default), or deleted_by

  • sort_order - asc or desc

  • page / per_page - paginate through results. Maximum 200 records per page. Check "more_records": true in the response to know if more pages exist

 2. Get a single Recycle Bin record 

Endpoint: GET {api-domain}/crm/v8/settings/recycle_bin/{record_id}

This API fetches details of a specific deleted record by its ID.

This is most useful in integrations where the external system stores the CRM record ID at the time of creation.


NotesThe Recycle Bin API only returns metadata about deleted records, not the full record details. The response contains the record's id, display_name, module, owner, deleted_by, and deleted_time. If you need the full record details, you should restore the record first and then fetch it via the get records API.

 3. Restore Recycle Bin records 

Endpoint: POST {api-domain}/crm/v8/settings/recycle_bin/{record_id}/actions/restore

This API restores a specific deleted record by its ID. When a record is restored, any associated records that are also in the Recycle Bin, such as Notes, Attachments, or Activities, are restored automatically along with it. This is a key advantage over recreating the record from scratch, where all that history would be permanently lost.

Note: Records are only available in the Recycle Bin for 60 days after deletion. After that they are permanently deleted and cannot be restored via API or manually.

 4. Get Recycle Bin record count 

Endpoint : GET {api-domain}/crm/v8/settings/recycle_bin/actions/count

This API returns the total number of records currently present in the Recycle Bin.

For example, Zylker could run a nightly process that checks this endpoint first. If the count is zero, the job exits without making additional API calls.

Monitoring this count can also help detect unexpected spikes in deleted records, which may indicate faulty automation or synchronization issues.

 5. Delete Recycle Bin records 

Endpoints:

DELETE {api-domain}/crm/v8/settings/recycle_bin/{record_ID}

DELETE {api-domain}/crm/v8/settings/recycle_bin?ids={id1,id2,...}

DELETE {api-domain}/crm/v8/settings/recycle_bin?filters={filter_value}

This endpoint permanently deletes one or more records from the Recycle Bin. Unlike a regular delete that moves records to the Recycle Bin, this removes them with no possibility of recovery.

A common use case is compliance-driven data erasure. For example, when a customer requests permanent deletion of their data under regulations like GDPR, the record can first be deleted from its module and then permanently removed from the Recycle Bin.


Notes
When a record is deleted from the Recycle Bin, all its associated records like Notes, Attachments, Activities are also permanently deleted. If the total number of records exceeds 1000, the deletion is scheduled as a background job.

 6. Empty the Recycle Bin   

Endpoint: POST {api-domain}/crm/v8/settings/recycle_bin/actions/empty

This API permanently deletes all records currently present in the Recycle Bin.

This is useful at the end of a bulk data migration or a testing cycle, where large numbers of records have been deleted and need to be permanently purged without going through them individually.

Automating Deal recovery from the Recycle Bin  

Now that we've covered the available Recycle Bin APIs, let's put them to work by building a recovery workflow for Zylker's integration.

Recall that Zylker’s integration creates Deals in CRM whenever a new order is placed. If an order fails, the corresponding Deal may be deleted. Later, if the order is corrected, the integration needs to restore the original Deal so that the sales team can continue working with the same record and retain its associated history.

To automate this process, we can implement a recovery workflow that performs the following steps:

  1. Identify the deleted Deal that needs to be restored.

  2. Retrieve the corresponding record from the Recycle Bin.

  3. Restore the record programmatically.

  4. Perform post-restore updates so the sales team knows the record was recovered.

The function below demonstrates how this can be implemented using Deluge.

The function supports two recovery paths:

  • Direct restoration using a record ID when the integration already knows the Deal ID in CRM.

  • Search-based restoration using the Deal name and a time window, which helps locate the correct record when the ID is not available.

Once the Deal is restored, the function also performs a few post-restore actions:

  • Updates the Deal stage to Needs Analysis

  • Adds a note indicating that the Deal was restored and why

This keeps the sales team informed and preserves a clear activity history.

The function has three parameters:

  1. deal_name (string) - The name or partial name of the Deal to search for

  2. days (integer) - The number of days to look back from the current day

  3. record_id (string) - The CRM record ID of the deleted Deal, if known. 

The record_id parameter is optional. If provided, the function skips the search and restores the record directly. If not, it falls back to searching by deal_name and days. This makes the function flexible enough to handle both scenarios: integrations that track CRM record IDs externally, and those that don't.

Before you begin:

This function uses a Zoho OAuth connection named crm_oauth_connection to make authenticated API calls to the Recycle Bin endpoints internally. Before running the function, set it up as follows:

  1. Go to Setup > Developer Hub > Connections

  2. Click Create Connection

  3. Choose Zoho CRM as the service

  4. Set the connection name to crm_oauth_connection (this must match exactly what is used in the code)

  5. Add the following scopes:

    • ZohoCRM.modules.ALL

    • ZohoCRM.settings.recycle_bin.READ

    • ZohoCRM.settings.recycle_bin.UPDATE

  1. Click Create and Connect and complete the authorization

 

Note: If this connection expires at any point, the function will return an UnAuthenticated Connection error. Go back to the Connections page and reauthorize it to resolve this.


The full implementation of the recovery function is available for download here : restoreDeletedDeal

Let's briefly walk through the logic implemented in the function.

1. The recovery path

The function first determines which recovery path to follow based on whether a record_id is provided.

if(record_id != null && record_id.trim() != "")

If record_id is a non-empty string, the function restores the Deal directly using that ID. This is the most reliable approach because it avoids ambiguity and ensures that the correct record is restored.

If the ID is not provided, the function falls back to searching the Recycle Bin using the Deal name and a configurable time window.

2. Searching the Recycle Bin

When the record ID is unavailable, the function retrieves deleted records and filters them to locate the correct Deal.

The filtering logic ensures that:

  • Only records from the Deals module are considered

  • The Deal name matches the input

  • The record was deleted within the specified time window.

This helps narrow down the correct record and avoid restoring unrelated Deals.

if(moduleApiName == "Deals"

    && displayName.trim().toLowerCase().contains(trimmedName)

&& deletedDate >= lookbackDate)

3. Handling search results

If no matching records are found, the function returns a not found message. If exactly one match is found, its ID and name are stored and the function proceeds to the restore step. If multiple matches are found, the function returns a structured list instead of guessing which one to restore:

if(matchedRecords.size() > 1)

{

    resultMsg = "Multiple Deals found matching '" + deal_name + "'. Please call this function again with the correct record_id:\n";

    for each match in matchedRecords

    {

        resultMsg = resultMsg + "- ID: " + match.get("id")

            + " | Name: " + match.get("deal_name")

            + " | Deleted On: " + match.get("deleted_time")

            + " | Deleted By: " + match.get("deleted_by") + "\n";

    }

    return resultMsg;

}

The caller must review the list, identify the correct record, and call the function again with the record_id directly.

4. Restoring the Record

Once the correct record ID is confirmed, the function calls the Restore endpoint.

restoreResponse = invokeurl

[

    url: "https://www.zohoapis.com/crm/v8/settings/recycle_bin/" + matchedRecordId + "/actions/restore"

    type: POST

    connection: "crm_oauth_connection"

];

The response is checked for two possible success codes - SUCCESS for an immediate restore, and SCHEDULED when the record has more than 1000 associated records and the restore runs as a background job. Both are handled as successful outcomes with different return messages.

5. Post-restore updates

After a successful restore, the function updates the Deal stage and adds a Note:

dealUpdate.put("Stage", "Needs Analysis");

zoho.crm.updateRecord("Deals", matchedRecordId.toLong(), dealUpdate);

noteContent = "Deal restored by " + currentUserName + " on " + currentDate + ". Reason: Order corrected.";

zoho.crm.createRecord("Notes", note);

Both updates are placed after the restore call. If the restore fails, neither runs, keeping the CRM data consistent.

Calling the function via REST API  

One of the powerful capabilities of Zoho CRM is that standalone Deluge functions can be exposed as REST API endpoints and called from any external system. This is what allows Zylker's e-commerce backend to trigger the recovery workflow directly whenever an order is corrected.

Enabling the Function as a REST API  

Once the function is saved, follow these steps to expose it as a REST API:

  1. Go to Setup > Developer Hub > Functions

  2. Click the (three dots) next to the corresponding function (restoreDeletedDeal)

  3. Click REST API

  4. Enable the OAuth2 slider

  5. Copy the endpoint URL shown

  6. Click Save.

The endpoint will be in the following format:

POST https://www.zohoapis.com/crm/v7/functions/{function-name}/actions/execute?auth_type=oauth

While calling the function, arguments must be passed in the request body as a form-data parameter named arguments, with the values as a JSON string.

Sample: {"deal_name":"Zylker","days":10,"record_id":""}

Required scope: ZohoCRM.functions.execute.CREATE

Conclusion  

The Recycle Bin API is a powerful but often overlooked capability in Zoho CRM. As we've seen in Zylker's scenario, restoring deleted records programmatically isn't just a convenience. It is a data integrity requirement for integrations that need to maintain a consistent, unbroken history of records across systems.

We hope this post helps you build more resilient and data-safe integrations on Zoho CRM. If you have questions or want to share how you've used the Recycle Bin API in your own integrations, drop a comment below!

 

 



      Zoho Campaigns Resources


        • Desk Community Learning Series


        • Digest


        • Functions


        • Meetups


        • Kbase


        • Resources


        • Glossary


        • Desk Marketplace


        • MVP Corner


        • Word of the Day


        • Ask the Experts


          • 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 #226: Using ZRC in Client Script

            Hello everyone! Welcome to another week of Kaizen. In today's post, lets see what is ZRC (Zoho Request Client) and how we can use ZRC methods in Client Script to get inputs from a Salesperson and update the Lead status with a single button click. In this
          • Kaizen #222 - Client Script Support for Notes Related List

            Hello everyone! Welcome to another week of Kaizen. The final Kaizen post of the year 2025 is here! With the new Client Script support for the Notes Related List, you can validate, enrich, and manage notes across modules. In this post, we’ll explore how
          • Kaizen #217 - Actions APIs : Tasks

            Welcome to another week of Kaizen! In last week's post we discussed Email Notifications APIs which act as the link between your Workflow automations and you. We have discussed how Zylker Cloud Services uses Email Notifications API in their custom dashboard.
          • Kaizen #216 - Actions APIs : Email Notifications

            Welcome to another week of Kaizen! For the last three weeks, we have been discussing Zylker's workflows. We successfully updated a dormant workflow, built a new one from the ground up and more. But our work is not finished—these automated processes are

          Zoho CRM Plus Resources

            Zoho Books Resources


              Zoho Subscriptions Resources

                Zoho Projects Resources


                  Zoho Sprints Resources


                    Zoho Orchestly Resources


                      Zoho Creator Resources


                        Zoho WorkDrive Resources



                          Zoho CRM Resources

                          • CRM Community Learning Series

                            CRM Community Learning Series


                          • Tips

                            Tips

                          • Functions

                            Functions

                          • Meetups

                            Meetups

                          • Kbase

                            Kbase

                          • Resources

                            Resources

                          • Digest

                            Digest

                          • CRM Marketplace

                            CRM Marketplace

                          • MVP Corner

                            MVP Corner




                            Zoho Writer Writer

                            Get Started. Write Away!

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

                              Zoho CRM コンテンツ



                                ご検討中の方

                                  • Recent Topics

                                  • Can I import MSG files into Microsoft 365 without Outlook?

                                    Yes, absolutely. You do not need Outlook installed to import MSG files into Microsoft 365. Aryson MSG file Converter is a dedicated tool that eliminates the Outlook dependency entirely, making the migration process simple and efficient for all users.
                                  • Feature Request - A Way To Search Item Groups

                                    Hi Inventory Team, I can't find any way to filter or search by fields of Item Groups. It would be great to see that functionality added. I have a use case where a single product might come from 5 or more suppliers and each supplier's item is an Item in
                                  • Zoho Books/Inventory - Update Marketplace Sales Order via API

                                    Hi everyone, Does anyone know if there is a way to update Sales Orders created from a marketplace intigration (Shopify in this case) via API? I'm trying to cover a scenario where an order is changed on the Shopify end and the changes must be reflected
                                  • Ticket id issues

                                    When I reply a ticket from desktop, it doesn't have ticket id in the subject and it's great. When I reply a ticket from Zoho desk mobile, Zoho adds ticket id in the subject and I don't want that. Please help in this matter.
                                  • Advanced email configuration - agent's name vs. department name

                                    We currently have all four Advanced Configuration options turned ON at the Global-level (Channels > Email > Advanced Configuration) - including the "Show Agent name in Ticket replies and outgoing emails" option. We also had that same option turned ON
                                  • Add Bounced as an Email Action / Notification for Bounced Emails

                                    This is one of the hard requirements for the clients we're servicing. They want to get an internal email notification whenever the email they sent to their contacts have bounced, so that they can look into it and update the email address. Currently, the
                                  • 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
                                  • not able to convert pdf to jpg and other forms and vice versa.

                                    i want to change my pdf to jpg, word, etc and some times jpg to pdf. i don't know how to do in this.
                                  • What’s New in Zoho Analytics - March 2026

                                    Hello Users! In this month's update, we bring improvements across integrations, security, reporting, and analytics capabilities to help you work with your data more efficiently and with greater control. Explore what’s new and see how these enhancements
                                  • Zoho People > Performance Management > Appraisal cycle

                                    Hello All I am using this 2 users to test out how it work on Performance Management User 1 - Reportee User 2 - Reporting Manager : Li Ting Haley User 1 : Self Appraisal Error How do i fix this error?
                                  • SalesIQ Tip for Admins: Guide Operators in Real-time Without Interrupting the Chat

                                    Consider this. You're a supervisor and you're looking through the active conversations. An associate is mid-chat with a high-value prospect. The prospect asks something unexpected, maybe about a tailor-made subscription plan or a bulk discount that’s
                                  • Early Access: Check Printing in Zoho Books

                                    Hello Everyone,   Are you constantly writing checks to pay your vendors?   We've got a great news to share with you! You can now pay your vendors by writing and printing a check directly from Zoho Books. The feature is ready and we'll be rolling it out to our customers in phases.  It is available in the  US Edition of Zoho Books and also in the Global edition, where the country is selected as USA and the currency is USD.   Here’s a summary of what’s possible:   1. Write and print a check. 2. Make
                                  • Connecting Zoho Inventory to ShipStation

                                    we are looking for someone to help connect via API shipStation with Zoho inventory. Any ideas? Thanks. Uri
                                  • Syncing zoho books into zoho crm

                                    I was wondering how I can use zoho books in crm as I have been using them separately and would like to sync the two. Is this possible and if so, how? Thanks
                                  • Zoho no support response.

                                    Problem is Zoho support seems to be just a concept. Just completing my trial, am ready to purchae 3 user subscriptions pending answer to a question, submitted two suport request during my trial that weren't responded to. Gave up trying the 888 line. Hard to imagine my production data in hosting environment with no support response.
                                  • Updating transaction number series for fiscal year 2026-2027 in Zoho POS

                                    A fiscal year or financial year is a 12-month period that businesses follow to manage and track their financial activities such as expenses, revenue, and taxes. This doesn't need to match the calendar year (JAN-DEC) and varies based on region, and tax
                                  • Lack of Looping and Carry-Forward Functionality in Zoho Survey

                                    Zoho Survey currently does not support looping or carry-forward functionality, meaning it is not possible to dynamically generate follow-up questions based on each option selected in a previous question or to pipe selected responses (such as {Looping
                                  • Forecast in Zoho CRM Just Got Smarter with an upgraded Zia Intelligence

                                    Hello Everyone, We are here with an interesting enhancement to Forecasts in Zoho CRM — Enhanced Zia Insights for your sales Forecast. Imagine a regional sales manager reviewing their team’s performance using forecasts in Zoho CRM. Instead of switching
                                  • Update TDS and TCS rates for Income Tax Act, 2025 (effective April 1, 2026)

                                    Hello everyone, The Income-tax Rules, 2026 (G.S.R. 198(E), dated March 20, 2026) have been notified, marking a significant structural shift in India’s direct tax framework. From April 1, 2026, the Income Tax Act, 2025 replaces the Income Tax Act, 1961.
                                  • Service line items

                                    Hello Latha, Could you please let me know the maximum number of service line items that can be added to a single work order? Thanks, Chethiya.
                                  • Automation Series: Auto-assign Resources as Task Owners

                                    In Zoho Projects, task ownership can be set automatically during task creation, allowing resources to be assigned based on the task name. Resources are work equipment or tools added to the portal to monitor their usage across projects. They can be assigned
                                  • Subform edits don't appear in parent record timeline?

                                    Is it possible to have subform edits (like add row/delete row) appear in the Timeline for parent records? A user can edit a record, only edit the subform, and it doesn't appear in the timeline. Is there a workaround or way that we can show when a user
                                  • AI secretary

                                    In our company, Claude is the secretary and creates inquiries and schedules from Gmail. You no longer have to enter them yourself. The secret is that we created an MCP server that connects to CRM. https://x.com/Mac_nishio/status/1917954562566328694
                                  • 5 small changes to Recruit that make a big difference

                                    Sometimes, the biggest improvements aren’t new features, they’re small changes that make everyday actions feel smoother. Over the past few weeks, we’ve made a few such updates across Zoho Recruit. They’re subtle, but together, they remove friction from
                                  • Project Management Bulletin: March, 2026

                                    We are passionate about equipping our users with efficient solutions that help them run their businesses successfully. Our collective efforts over the past 2 years have culminated in the launch of Sprints 3.0— built with reliable features, impactful integrations,
                                  • New security enhancements for portal users: MFA and password management

                                    Hello everyone, We are excited to announce three major security enhancements that are now available to portal users in Zoho CRM: Organization-wide multi-authentication for portal users - Admins can enforce multi-factor authentication across the entire
                                  • [Free Webinar] Learning Table Series 2026 – Customer agreement & contract management using Zoho Creator

                                    Hello everyone, We’re excited to announce the next session in Learning Table Series 2026, where we will continue with our purpose-driven approach—focusing on how Zoho Creator’s features help solve real-world business challenges. Each session in this series
                                  • Zoho Payroll's USA and KSA editions are available in Zoho One!

                                    Greetings! We’re excited to share that Zoho Payroll, currently available only in India and the UAE, is now introducing the KSA (Kingdom of Saudi Arabia) edition and the USA (United States of America) edition, and these editions are now available in Zoho
                                  • Looking for Guidance on Building a Zoho Website

                                    I'm exploring the possibility of building a custom website with specific features using Zoho as an alternative platform. My goal is to create something similar to https://gtasandresapk.com , with the same kind of functionality and user experience. I'd
                                  • Multilingual website feature

                                    Would be a great feature to have. I saw that this feature was available for backstage. I think it could be done for zoho sites too.
                                  • [Webinar] Modernize your sales engine with agentic analytics

                                    Traditional sales decision-making methods aren't cut out for modern businesses. Leveraging AI in sales helps businesses actively respond to the changing dynamics of the market. Agentic AI is letting sales teams across industries make better decisions
                                  • Built-in Date Functions in Zoho Analytics Query Tables

                                    I have a doubt about whether Zoho Analytics Query Tables provide built-in functions for start date, end date, and the current month
                                  • Zoho Commerce in multiple languages

                                    When will you be able to offer Zoho Commerce in more languages? We sell in multiple markets and want to be able to offer a local version of our webshop. What does the roadmap look like?
                                  • Nimble enhancements to WhatsApp for Business integration in Zoho CRM: Enjoy context and clarity in business messaging

                                    Dear Customers, We hope you're well! WhatsApp for business is a renowned business messaging platform that takes your business closer to your customers; it gives your business the power of personalized outreach. Using the WhatsApp for Business integration
                                  • Connectivity issues with Google Calendar and third-party integrations

                                    Description: We are currently experiencing a critical failure with Zoho CRM third-party connections. This issue is heavily affecting our primary workflow. Symptoms: Sync Failure: Existing Zoho CRM to Google Calendar connections have been failing for approximately
                                  • Dynamic image in form works in the app but not on the customer portal.

                                    img = frm_Fichas[ID == input.Nombre].Foto; imgno = Nophoto[ID2 = 1].Image; if(len(img) > 1) { img = img.replaceAll("/sharedBy/appLinkName/",zoho.appuri); img = img.replaceAll("viewLinkName","Fichas_de_personal_public"); img = img.replaceAll("fieldName","Foto");
                                  • Incorrect Functioning of Time Logs API (Version 3)

                                    We need to fetch the list of time logs for each task for our company internal usage. We are trying to achieve it by using the next endpoint: https://projects.zoho.com/api-docs#bulk-time-logs#get-all-project-time-logs Firstly, in the documentation the
                                  • How can I export all Deluge code across the application?

                                    I’m working on a application with multiple forms, reports, and HTML views, where Deluge scripts are used across workflows, field actions, and custom functions. Is there a way to export all Deluge scripts into a single file for easier search?
                                  • First Name in Mail

                                    While sending a mail/message to the user, I want only the first name to be displayed—for example: “Hi John” instead of the full name using "Hi ${Name_Field}"
                                  • Can you import projects into Zoho Projects yet?

                                    I see some very old posts asking about importing project records into Zoho Projects. But I can't find anything up to date about the topic. Has this functionality been added? Importing tasks is helpful. But we do have a project where importing projects
                                  • Next Page