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!

 

 



      • 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

        • Recent Topics

        • New Account, Setting up Domain Question

          Hello, I recently set up a new account with a custom domain. But after paying and setting up my account, it says OpenSRS actually owns the domain, and I have to sign up with them to host my site. But OpenSRS wants to charge me $95, which is ridiculous.
        • 【開催報告】東京 Zoho ユーザー交流会 NEXUS vol.1 ~ データドリブン経営・少人数組織のCRM活用・AIエージェントの最前線 ~

          ユーザーの皆さん、こんにちは。 コミュニティグループの中野です。 2026年3月27日(金)、東京・新橋にて「東京 Zoho ユーザー交流会 NEXUS vol.1」が開催されました。 今回は「マーケティング領域のZoho 活用法 × AI」をテーマに、ユーザーさん2名による事例セッション、Zoho 社員によるAIセッションなどを実施しました。 ご参加くださったユーザーの皆さま、ありがとうございました! この投稿では、当日のセッションの様子や使用した資料を紹介しています。残念ながら当日お越しいただけなかった方も、ぜひチェックしてみてください。
        • Monthly Webinar : Getting Started with Zoho LandingPage

          Our monthly Getting Started with Zoho LandingPage webinar is back! If you're building your first page and want a little guidance, this is where to start. Learn how landing pages fit into your strategy, generate leads, and improve conversions. Here’s what
        • Mass emails - Allow preview of which emails will receive the email based on the criteria

          Feature request. Please allow us to view and confirm the exact recipients of the mass emails based on the criteria we've chosen before sending. It can be quite sensitive if you send the mass email to some wrong accounts accidently, so it would be great
        • Limitation in Dynamic Constant Sum Based on Previous Question Selections in Zoho Survey

          Zoho Survey supports the Constant Sum question type, allowing respondents to distribute a fixed total (such as 100) across a set of options. However, it does not support dynamically populating these options based on selections made in a previous question.
        • SAP Business One(B1) integration is now live in Zoho Flow

          We’re excited to share that SAP Business One (B1) is now available in Zoho Flow! This means you can now build workflows that connect SAP B1 with other apps and automate routine processes without relying on custom code. Note: SAP Business One integration
        • sync two zoho crm

          Hello everyone. Is it possible to sync 2 zoho crm? what would be the easiest way? I am thinking of Flow. I have a Custom Module that I would like to share with my client. We both use zoho crm. Regards.
        • Showing the map along with mileage expense

          When you use the GPS to track mileage, it shows you the map of the actual path travelled. It would be very useful and practical to save that map with the mileage expense, so that when the report is created, it provides a map of each mileage expense associated
        • Import MSG to Yandex Mail Account | Fast & Reliable Solution

          If you are facing problem to import MSG files to Yandex Mail account can be challenging if done manually, especially when handling multiple files. A reliable solution is using the MacGater Mac MSG Converter, which simplifies the entire process with accuracy
        • Copy all reports in a folder

          I currently have a database that I need to create multiple charts filtered by market. All of the charts are identical, I just change to of the filters and then I have the next market's set of charts. The only way I've been able to copy charts (reports)
        • OpenURL working Intermittently

          Never had this issue before, everything was working fine up to a few days ago. We have a buttons on reports to open forms with pre-filled fields. Now, there are instances where it will throw and error and gives no feedback. What is really strange is not
        • Zoho Recruit mailserver get blocked by Microsoft!

          Hi, We have experienced this issue twice now, where Zoho Recruit outbound IP addresses are being blocked by Microsoft. We are confident that Microsoft is the blocking party, as all outbound emails to candidates with @hotmail.com, @live.com, and @outlook.com
        • Calculate Hours Minutes Sec in Zoho Creator Using Deluge

          check_In = "8-Aug-2023 10:00:00".toDateTime().toLong(); checkout = "8-Aug-2023 18:00:00".toDateTime().toLong(); //difference = start.timeBetween(end); check_In = "8-Aug-2023 17:56:50".toDateTime().toLong(); checkout = "8-Aug-2023 18:00:00".toDateTime().toLong();
        • Build Smarter Apps with AI in Zoho Creator

          Build Smarter Apps with AI in Zoho Creator This is truly the era of AI, and businesses that adapt now will lead tomorrow. Zoho is already moving ahead in this direction, continuously evolving its platform with powerful AI capabilities. With Zoho Creator,
        • Zia Dashboard Insights : turn your dashboard into decisions

          When you look at a chart or KPI in a dashboard, you would possibly see something like: Revenue: $2.4M ↓ 18% vs last month. It can be a positive growth or a negative one, or a dip in revenue, a spike in deals, a slowdown in renewals—all you usually see
        • Tickets without registration

          Hi, would it be possible to give customers the opportunity to be able to read their tickets without registration?
        • Zoho Desk Answer Bot vs. Zia Agents – Knowledge Base & Ticket Access

          Hi everyone, I’m currently evaluating AI options in Zoho Desk and ran into some limitations with the Answer Bot: Answer Bot limitations Only uses Knowledge Base articles No access to tickets Limited control over sources: Either one Help Center or all
        • Como estruturar automações eficientes no Zoho Creator

          Como estruturar automações eficientes no Zoho Creator Introdução No contexto de aplicações empresariais, automação não é apenas uma conveniência, é um fator crítico para ganho de produtividade, redução de erros e escalabilidade operacional. O Zoho Creator
        • Changing the status of a work-order

          Is there a way to change the status of a work-order?
        • Online Payment Fees

          We don't take many online credit card payments so the merchant service provider (PayPal) charges us the 2.9% fee for processing the amount. I would like the ability for the fee to be automatically added to the total amount for "ease of payment". We'd
        • What is a realistic turnaround time for account review for ZeptoMail?

          On signing up it said 2-3 business days. I am on business-day 6 and have had zero contact of any kind. No follow-up questions, no approval or decline. Attempts to "leave a message" or use the "Contact Us" form have just vanished without a trace. It still
        • Zia Agents in Zoho CRM: a better way to set up digital employees

          Hello everyone, If you've been using Zia Agents in Zoho CRM, so far using Connections was the only deployment method you're familiar with. You create an agent in Zia Agents (define its objective, write instructions, use tools, add knowledge base) and
        • Bank Feeds

          Since Friday my bank feeds wont work. I have refreshed feeds, deactivate and reactivate and nothing is working
        • Logged out

          Hi, just been working on a sheet when a pop up box appeared telling me I'm going to be logged out in x number of seconds and if I reload I may lose any edits, or words to that effect. It did indeed log me out and I did indeed lose my last edits. Any idea
        • Zoho API

          I have little experience with API. I'm trying to get a Custom API working with Zoho creator. I have created a Custom API and created an Endpoint URL, but i get a 9400 error code "The provided HTTP method is not valid for this custom API". Based off the
        • #157127950

          Where did my initial question go?
        • Zoho writer unable to merge documents to PDF with basic fonts in Hebrew or fonts from my computer

          I created several forms that will be merged into PDF files through Zoho Writer and I am unable to receive the PDF in the basic fonts of the Hebrew language or in the fonts I have on my computer. The writer exports to PDF an exchange font that looks very
        • How I Implemented Subscription-Based Access Control and Expiry Handling in Zoho Creator

          I recently worked on a use case where users come into the application to request a service, but they should only be able to continue the process after completing a subscription. The challenge was not just controlling access, but also making sure that
        • Zoho Forms API

          Is there any way to get all form entry list using API? Looking forward to hear from you
        • Zoho Projects : Task should auto-update to 'In Progress' if timer started

          Namaskaram. Right now, if a Task's timer is started, the Task stays in 'Not Started' status. One has to manually update it to 'In Progress'. From a #uxdesign standpoint, it is an unnecessarily two step process to start working on a task. It would be better that, if I start the timer on a task, it should automatically change to 'In Progress' status. Crafted with ❤️ Zoho Gurus | Zoho One Practice Team @ CubeYogi Zoho Authorised Partner | 7+ Yrs | 200+ Projects | 100+ Customers
        • Laatste facturen en betalingen niet zichtbaar in mijn account

          Wij gebruiken ZOHO invoice al jaren, maar sinds afgelopen week is mijn laatst verzonden factuur niet zichtbaar in mijn account, en tevens de laatst betaalde facturen zie ik niet. Hoe kan dit? Ik heb de pagina al diverse keren gerefreshed.
        • Undelivered Mail uncategorized-bounce errors when sending invoices

          Recently we have been getting Undelivered Mail bounce notification when sending invoices. Reason: uncategorized-bounce Some go through no problem some bounce back. We recently sent 10 invoices, 6 received bounce notifications. After reaching out to the
        • 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.
        • Next Page