> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to delete and restore an envelope

> Learn how to delete and restore an envelope

This topic demonstrates how to delete and undelete an envelope. Deleting an envelope in Docusign means to move the envelope into the predefined folder Recycle Bin; undeleting an envelope means to move the envelope out of the Recycle Bin and into another folder as you desire: either another predefined folder, such as Inbox or Sent Items, or into any other folder you’ve defined in your Docusign account.

Docusign also provides other options for removing envelopes: you can void an envelope that’s still in progress (not completed), making it invalid; or you can purge an envelope in any state, which permanently destroys the envelope from your account. Both voiding and purging are one-way operations and cannot be reversed, unlike deleting.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element      | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \{API_ACCOUNT_ID} | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                                                                                           |
| \{BASE_PATH}      | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/restapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production.                                                             |
| \{ENVELOPE_ID}    | A [GUID](http://guid.one/) value that identifies a Docusign [envelope](/docs/esign-rest-api/esign101/concepts/envelopes). This value is automatically generated by Docusign when the envelope is created.                                                                                                                                                                          |
| \{FOLDER_ID}      | A [GUID](http://guid.one/) value that identifies the folder into which you want to move the selected envelope(s). This value is automatically generated by Docusign when the folder is created. For the default Docusign folders Inbox, Sent Items, and Recycle Bin, you can also use the predefined strings “inbox”, “sentitems”, and “recyclebin” , respectively, as folder IDs. |

## Step 1. Obtain your OAuth token

To make the API call shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Confidential Authorization Code Grant](/platform/auth/authcode#confidential-authorization-code-grant) for guidance on your options to get an Confidential Authorization Code Grant  OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}"
    '--header' "Accept: application/json"
    '--header' "Content-Type: application/json")
```

**`C#`**

```csharp title="C#"
var docusignClient = new DocuSignClient(basePath);
docusignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
```

**`Java`**

```java title="Java"
		ApiClient apiClient = createApiClient(session.getBasePath(), user.getAccessToken());
```

**`Node.js`**

```javascript title="Node.js"
const dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
const foldersApi = new docusign.FoldersApi(dsApiClient);
```

**`PHP`**

```php title="PHP"
$foldersApi = $clientService->getFoldersApi();
```

**`PowerShell`**

```text title="PowerShell"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", "Bearer $accessToken")
$headers.add("Content-Type", "application/json")
```

**`Python`**

```python title="Python"
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
folders_api = FoldersApi(api_client)
```

**`Ruby`**

```ruby title="Ruby"
folders_api = create_folders_api(args)
```

## Step 3. Construct the request body

Next, create the request body. The request body for this API call consists of an array of envelope IDs; you can include as many as you wish. For this how-to, view a sample envelope in your developer account (create one if you need to) and select **Envelope ID** to view the GUID value; then substitute that GUID for \{ENVELOPE_ID} in the array.

**`Bash`**

```bash title="Bash"
printf '{
  "envelopeIds": [
    "%s"
  ]
}' "${envelope_id}" > $request_body
```

**`C#`**

```csharp title="C#"
var foldersRequest = new FoldersRequest
{
    EnvelopeIds = new List<string> { envelopeId },
};
```

**`Java`**

```java title="Java"
FoldersRequest foldersRequest = new FoldersRequest();
foldersRequest.setEnvelopeIds(Collections.singletonList(envelopeId));
```

**`Node.js`**

```javascript title="Node.js"
const foldersRequest = docusign.FoldersRequest.constructFromObject({
  envelopeIds: [args.envelopeId],
});
```

**`PHP`**

```php title="PHP"
$foldersRequest = new FoldersRequest([
    'envelope_ids'   => [$envelopeId],
]);
```

**`PowerShell`**

```text title="PowerShell"
@{
    envelopeIds = @("$envelopeId")
} | ConvertTo-Json -Depth 32 > $requestData
```

**`Python`**

```python title="Python"
folders_request = FoldersRequest(
    envelope_ids=[args["envelope_id"]]
)
```

**`Ruby`**

```ruby title="Ruby"
folders_request = DocuSign_eSign::FoldersRequest.new
folders_request.envelope_ids = [args[:envelope_id]]
```

## Step 4. Call the eSignature REST API to delete your envelope

Now that you have constructed your API headers and request body, make a PUT request to the [Folders:moveEnvelopes](/docs/esign-rest-api/reference/folders/folders/moveenvelopes) endpoint and include the request body to specify the envelope to move to the Recycle Bin. Here’s how you make the call, but make sure to substitute your API account ID for \{API_ACCOUNT_ID}.

**`Bash`**

```bash title="Bash"
curl --request PUT "${base_path}/v2.1/accounts/${account_id}/folders/recyclebin" \
    "${Headers[@]}" \
    --data-binary @${request_body}
```

**`C#`**

```csharp title="C#"
var response = foldersApi.MoveEnvelopesWithHttpInfo(accountId, DeleteFolderId, foldersRequest);
response.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
response.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

return response.Data;
```

**`Java`**

```java title="Java"
var moveEnvelopes = foldersApi.moveEnvelopesWithHttpInfo(accountId, RECYCLE_BIN_FOLDER_ID, foldersRequest);
Map<String, List<String>> headers = moveEnvelopes.getHeaders();
java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
java.util.List<String> reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}
return moveEnvelopes.getData();
```

**`Node.js`**

```javascript title="Node.js"
var response = await foldersApi.moveEnvelopes(args.accountId, args.deleteFolderId, { foldersRequest }, (error, data, response) => {
    const headers = response?.headers;

    const remaining = headers?.['x-ratelimit-remaining'];
    const reset = headers?.['x-ratelimit-reset'];

    if (remaining && reset) {
      const resetInstant = new Date(Number(reset) * 1000);

      console.log(`API calls remaining: ${remaining}`);
      console.log(`Next Reset: ${resetInstant.toISOString()}`);
    }
});
return response.data;
```

**`PHP`**

```php title="PHP"
$response = $foldersApi->moveEnvelopesWithHttpInfo($accountId, self::DELETE_FOLDER_ID, $foldersRequest);

$remaining = $response[2]['X-RateLimit-Remaining'] ?? null;
$reset = $response[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}
return $response[0];
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/folders/${recycle_bin_folder_id}" `
    -Method 'PUT' `
    -Headers $headers `
    -InFile (Resolve-Path $requestData).Path `
    -OutFile $response `
```

**`Python`**

```python title="Python"
(results, status, headers) = folders_api.move_envelopes_with_http_info(account_id=args["account_id"], folder_id=args["delete_folder_id"], folders_request=folders_request)

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
results, _status, headers = folders_api.move_envelopes_with_http_info(args[:account_id], args[:delete_folder_id], folders_request)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Step 5. Call the eSignature REST API to find the folder id

Find the Destination Folder ID: To restore an envelope to a specific folder, you must first get the folder's unique ID. You can find this by making a GET request to the Docusign [Folders:list](/docs/esign-rest-api/reference/folders/folders/list) API endpoint. This call returns a list of all the folders in your account; each folder’s properties include, among others, its name and corresponding folderId. You can then extract the folderId for the folder you want to move the envelope to; you’ll do that in **Step 6.**

**`Bash`**

```bash title="Bash"
RESPONSE=$(curl --request GET \
    "${Headers[@]}" \
    "${base_path}/v2.1/accounts/${account_id}/folders")

# Find the specific folder entered and extract its folderId

folder_id=$(echo "${RESPONSE}" | grep -oi "\"name\":\"${destination_folder_name}\",\"type\":\"[^\"]*\",\"owner\":{[^\}]*},\"folderId\":\"[^\"]*\"" | sed 's/.*"folderId":"//' | sed 's/"$//')
```

**`C#`**

```csharp title="C#"
if (folder.Folders != null && !folder.Folders.Count.Equals(0))
{
    Folder nestedFolder = GetFolderByName(folder.Folders, targetName);
    if (nestedFolder != null)
    {
        return nestedFolder;
    }
}
```

**`Java`**

```java title="Java"

    public static FoldersResponse getFolders(
            ApiClient apiClient,
            String accountId) throws Exception {
        FoldersApi foldersApi = new FoldersApi(apiClient);

        var callListResponse = foldersApi.callListWithHttpInfo(accountId, foldersApi.new CallListOptions());
        Map<String, List<String>> headers = callListResponse.getHeaders();
        java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
        java.util.List<String> reset = headers.get("X-RateLimit-Reset");

        if (remaining != null & reset != null) {
            Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
            System.out.println("API calls remaining: " + remaining);
            System.out.println("Next Reset: " + resetInstant);
        }
        return callListResponse.getData();
    }

    public static Folder getFolderIdByName(List<Folder> folders, String targetName) {
        for (Folder folder : folders) {
            if (folder.getName().equals(targetName)) {
                return folder;
            }

            if (folder.getFolders() != null && !folder.getFolders().isEmpty()) {
                Folder nestedFolder = DeleteRestoreEnvelopeService.getFolderIdByName(folder.getFolders(), targetName);
                if (nestedFolder != null) {
                    return nestedFolder;
                }
            }
        }
        return null;
    }
```

**`Node.js`**

```javascript title="Node.js"
response = await foldersApi.list(args.accountId, (error, data, response) => {
    const headers = response?.headers;

    const remaining = headers?.['x-ratelimit-remaining'];
    const reset = headers?.['x-ratelimit-reset'];

    if (remaining && reset) {
      const resetInstant = new Date(Number(reset) * 1000);

      console.log(`API calls remaining: ${remaining}`);
      console.log(`Next Reset: ${resetInstant.toISOString()}`);
    }
});
return response.data;
```

**`PHP`**

```php title="PHP"
$subFolders = $folder->getFolders();
if (!empty($subFolders)) {
    $nestedFolder = self::getFolderByName($subFolders, $targetName);
    if ($nestedFolder !== null) {
        return $nestedFolder;
    }
}
        }

        return null;
```

**`PowerShell`**

```text title="PowerShell"
function Get-FolderIdByName {
    param (
        [object]$folders,
        [string]$targetName
    )

    foreach ($folder in $folders) {
        # Check this folder
        if ($folder.name -eq $targetName) {
            return $folder.folderId
        }

        # If this folder has subfolders, search inside them
        if ($folder.folders) {
            $result = Get-FolderIdByName -folders $folder.folders -targetName $targetName
            if ($result) {
                return $result
            }
        }
    }

    return $null
}

Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/folders" `
    -Method 'GET' `
    -Headers $headers `
    -OutFile $response

$folders = $(Get-Content $response | ConvertFrom-Json).folders
$folderId = Get-FolderIdByName -folders $folders -targetName $destinationFolderName
```

**`Python`**

```python title="Python"
(results, status, headers) = folders_api.list_with_http_info(account_id=args["account_id"])

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
results, _status, headers = folders_api.list_with_http_info(args[:account_id])

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Step 6. Call the eSignature REST API to undelete your envelope

Call the [Folders:moveEnvelopes](/docs/esign-rest-api/reference/folders/folders/moveenvelopes) method with the ID of the envelope you want to undelete, the folder ID of the folder you want to move it to, and “recyclebin” as fromFolderId. The returned data will include the envelope ID moved from the recycle bin or Deleted folder. Deleted envelopes can be undeleted only within 24 hours from the Docusign Recycle Bin; thereafter, they are no longer accessible from your Docusign account.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/eSignature/eg045DeleteRestoreEnvelope.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Examples/DeleteRestoreEnvelope.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/eSignature/examples/EG045ControllerDeleteRestoreEnvelope.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/examples/deleteRestoreEnvelope.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/eSignature/DeleteRestoreEnvelopeService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/eSignature/eg045DeleteRestoreEnvelope.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/eSignature/examples/eg045_delete_restore_envelope.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/master/app/services/e_sign/eg045_delete_restore_envelope_service.rb).

**`Bash`**

```bash title="Bash"
curl --request PUT "${base_path}/v2.1/accounts/${account_id}/folders/${folder_id}" \
    "${Headers[@]}" \
    --data-raw '{
      "envelopeIds": [
        "'${envelope_id}'"
      ],
      "fromFolderId": "recyclebin"
    }'
```

**`C#`**

```csharp title="C#"
var response = foldersApi.MoveEnvelopesWithHttpInfo(accountId, folderId, foldersRequest);
response.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
response.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

return response.Data;
```

**`Java`**

```java title="Java"

    public static FoldersResponse moveEnvelopeToFolder(
            ApiClient apiClient,
            String accountId,
            String envelopeId,
            String folderId,
            String fromFolderId) throws Exception {
        FoldersApi foldersApi = new FoldersApi(apiClient);

        FoldersRequest foldersRequest = new FoldersRequest();
        foldersRequest.setFromFolderId(fromFolderId);
        foldersRequest.setEnvelopeIds(Collections.singletonList(envelopeId));

        var moveEnvelopesResponse = foldersApi.moveEnvelopesWithHttpInfo(accountId, folderId, foldersRequest);
        Map<String, List<String>> headers = moveEnvelopesResponse.getHeaders();
        java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
        java.util.List<String> reset = headers.get("X-RateLimit-Reset");

        if (remaining != null & reset != null) {
            Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
            System.out.println("API calls remaining: " + remaining);
            System.out.println("Next Reset: " + resetInstant);
        }
        return moveEnvelopesResponse.getData();
    }
```

**`Node.js`**

```javascript title="Node.js"
const foldersRequest = docusign.FoldersRequest.constructFromObject({
  envelopeIds: [args.envelopeId],
  fromFolderId: args.fromFolderId,
});

var response = await foldersApi.moveEnvelopes(args.accountId, args.folderId, { foldersRequest }, (error, data, response) => {
    const headers = response?.headers;

    const remaining = headers?.['x-ratelimit-remaining'];
    const reset = headers?.['x-ratelimit-reset'];

    if (remaining && reset) {
      const resetInstant = new Date(Number(reset) * 1000);

      console.log(`API calls remaining: ${remaining}`);
      console.log(`Next Reset: ${resetInstant.toISOString()}`);
    }
});
return response.data;
```

**`PHP`**

```php title="PHP"
$response = $foldersApi->moveEnvelopesWithHttpInfo($accountId, $folderId, $foldersRequest);

$remaining = $response[2]['X-RateLimit-Remaining'] ?? null;
$reset = $response[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}
return $response[0];
```

**`PowerShell`**

```text title="PowerShell"
@{
    envelopeIds  = @("$envelopeId");
    fromFolderId = "$recycle_bin_folder_id"
} | ConvertTo-Json -Depth 32 > $requestData

# Create and send the folders request
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/folders/${folderId}" `
    -Method 'PUT' `
    -Headers $headers `
    -InFile (Resolve-Path $requestData).Path `
    -OutFile $response
```

**`Python`**

```python title="Python"
folders_request = FoldersRequest(
    envelope_ids=[args["envelope_id"]],
    from_folder_id=args["from_folder_id"]
)

(results, status, headers) = folders_api.move_envelopes_with_http_info(account_id=args["account_id"], folder_id=args["folder_id"], folders_request=folders_request)

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
folders_request = DocuSign_eSign::FoldersRequest.new
folders_request.envelope_ids = [args[:envelope_id]]
folders_request.from_folder_id = args[:from_folder_id]

results, _status, headers = folders_api.move_envelopes_with_http_info(args[:account_id], args[:folder_id], folders_request)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Expected response

If you run this code example from our Quickstart or launcher projects, you should see a JSON response similar to the code shown.

**`Sample response`**

```json title="Sample response"
{
    "envelopes": [
        {
            "envelopeId": "4b0d152e-xxxx-xxxx-xxxx-9d8ada5bdce8"
        }
    ]
}
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* See how to [Go-Live](/docs/esign-rest-api/go-live) with a completed app and find the base path for API calls in the production environment.