# Delete Document

Permanently deletes a specific document associated with a customer. This operation removes both the document metadata and the actual file content from storage. Use with caution as deleted documents cannot be recovered.

**Endpoint**

`DELETE/v2/customer/{customerId}/file/{id}`

**Link**

{% embed url="<https://stagep.tst-apidmndelss.com/openapi/v2.html#/operations/Customer_DocumentDelete>" %}

### **Request**

#### **Path Parameters**

| Parameter        | Type     | Description                             | Required | Example        |
| ---------------- | -------- | --------------------------------------- | -------- | -------------- |
| **`customerId`** | `string` | **Customer ID** that owns the document. | Yes      | `"cust_12345"` |
| **`id`**         | `string` | **Document unique ID** to delete.       | Yes      | `"doc_abc123"` |

#### **Headers**

| Key                 | Value              | Required |
| ------------------- | ------------------ | -------- |
| **`Authorization`** | `123`              | Yes      |
| **`Accept`**        | `application/json` | Yes      |

***

### **Response (200 OK)**

Returns a success confirmation message indicating the document was successfully deleted.

#### **Response Fields**

| Field         | Type      | Description                  | Example                           |
| ------------- | --------- | ---------------------------- | --------------------------------- |
| **`success`** | `boolean` | Operation success status.    | `true`                            |
| **`message`** | `string`  | Descriptive success message. | `"Document deleted successfully"` |

**Example Response:**

json

```
{
  "success": true,
  "message": "Document deleted successfully"
}
```

***

### **Examples**

#### **Request**

bash

```
curl -X DELETE 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_abc123' \
  -H 'Authorization: 123' \
  -H 'Accept: application/json'
```

#### **Successful Deletion Example**

**Request:**

bash

```
curl -X DELETE 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_pass123' \
  -H 'Authorization: 123' \
  -H 'Accept: application/json'
```

**Response:**

json

```
{
  "success": true,
  "message": "Document deleted successfully"
}
```

#### **Programming Language Examples**

**Python Delete Example**

python

```
import requests

def delete_document(customer_id, document_id, auth_token):
    url = f"https://stagep.tst-apidmndelss.com/v2/customer/{customer_id}/file/{document_id}"
    headers = {
        "Authorization": auth_token,
        "Accept": "application/json"
    }
    
    response = requests.delete(url, headers=headers)
    
    if response.status_code == 200:
        result = response.json()
        print(f"Success: {result['success']}")
        print(f"Message: {result['message']}")
        return True
    else:
        print(f"Error deleting document: {response.status_code} - {response.text}")
        return False

# Usage
delete_document("cust_12345", "doc_pass123", "123")
```

**JavaScript/Node.js Delete Example**

javascript

```
const https = require('https');

function deleteDocument(customerId, documentId, authToken) {
    return new Promise((resolve, reject) => {
        const options = {
            hostname: 'stagep.tst-apidmndelss.com',
            path: `/v2/customer/${customerId}/file/${documentId}`,
            method: 'DELETE',
            headers: {
                'Authorization': authToken,
                'Accept': 'application/json'
            }
        };

        const request = https.request(options, (response) => {
            let data = '';

            response.on('data', (chunk) => {
                data += chunk;
            });

            response.on('end', () => {
                if (response.statusCode === 200) {
                    const result = JSON.parse(data);
                    console.log('Success:', result.success);
                    console.log('Message:', result.message);
                    resolve(result);
                } else {
                    reject(new Error(`HTTP ${response.statusCode}: ${data}`));
                }
            });
        });

        request.on('error', (error) => {
            reject(error);
        });

        request.end();
    });
}

// Usage
deleteDocument('cust_12345', 'doc_pass123', '123')
    .then(result => console.log('Document deleted successfully'))
    .catch(error => console.error('Error:', error.message));
```

**Java Delete Example**

java

```
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DocumentDeleter {
    public static boolean deleteDocument(String customerId, String documentId, String authToken) {
        try {
            String urlString = String.format(
                "https://stagep.tst-apidmndelss.com/v2/customer/%s/file/%s",
                customerId, documentId
            );
            
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("Authorization", authToken);
            connection.setRequestProperty("Accept", "application/json");
            
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream())
                );
                String inputLine;
                StringBuilder response = new StringBuilder();
                
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                
                // Parse JSON response
                System.out.println("Response: " + response.toString());
                System.out.println("Document deleted successfully");
                return true;
            } else {
                System.err.println("Error deleting document: " + responseCode);
                return false;
            }
        } catch (IOException e) {
            System.err.println("Request error: " + e.getMessage());
            return false;
        }
    }
    
    // Usage
    public static void main(String[] args) {
        boolean success = deleteDocument("cust_12345", "doc_pass123", "123");
        System.out.println("Deletion successful: " + success);
    }
}
```

**PHP Delete Example**

php

```
<?php
function deleteDocument($customerId, $documentId, $authToken) {
    $url = "https://stagep.tst-apidmndelss.com/v2/customer/{$customerId}/file/{$documentId}";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: {$authToken}",
        "Accept: application/json"
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $result = json_decode($response, true);
        echo "Success: " . ($result['success'] ? 'true' : 'false') . "\n";
        echo "Message: " . $result['message'] . "\n";
        return true;
    } else {
        echo "Error deleting document: HTTP {$httpCode} - {$response}\n";
        return false;
    }
}

// Usage
deleteDocument("cust_12345", "doc_pass123", "123");
?>
```

#### **Common Delete Scenarios**

**1. Delete Rejected Document**

**Scenario**: Remove a document that was rejected during verification to allow re-upload.

**Request:**

bash

```
curl -X DELETE 'https://stagep.tst-apidmndelss.com/v2/customer/cust_12345/file/doc_rejected456' \
  -H 'Authorization: 123'
```

**Response:**

json

```
{
  "success": true,
  "message": "Document deleted successfully"
}
```

**2. Delete Temporary Document**

**Scenario**: Remove a temporary or test document that is no longer needed.

**Request:**

bash

```
curl -X DELETE 'https://stagep.tst-apidmndelss.com/v2/customer/cust_67890/file/doc_temp789' \
  -H 'Authorization: 123'
```

**Response:**

json

```
{
  "success": true,
  "message": "Document deleted successfully"
}
```

**3. Bulk Delete Script**

**Python script for deleting multiple documents:**

python

```
import requests

def delete_multiple_documents(customer_id, document_ids, auth_token):
    results = []
    for doc_id in document_ids:
        try:
            url = f"https://stagep.tst-apidmndelss.com/v2/customer/{customer_id}/file/{doc_id}"
            headers = {"Authorization": auth_token, "Accept": "application/json"}
            
            response = requests.delete(url, headers=headers)
            success = response.status_code == 200
            message = response.json().get('message') if success else f"HTTP {response.status_code}"
            
            results.append({
                'document_id': doc_id,
                'success': success,
                'message': message
            })
            
            print(f"Document {doc_id}: {'Success' if success else 'Failed'}")
            
        except Exception as e:
            results.append({
                'document_id': doc_id,
                'success': False,
                'message': str(e)
            })
            print(f"Document {doc_id}: Error - {e}")
    
    return results

# Usage
documents_to_delete = ["doc_123", "doc_456", "doc_789"]
results = delete_multiple_documents("cust_12345", documents_to_delete, "123")

# Print summary
success_count = sum(1 for r in results if r['success'])
print(f"\nSummary: {success_count}/{len(results)} documents deleted successfully")
```

***

### **Error Responses**

1. **Document Not Found**:

   json

   ```
   {
     "success": false,
     "message": "Document not found: doc_99999"
   }
   ```
2. **Customer Not Found**:

   json

   ```
   {
     "success": false,
     "message": "Customer not found: cust_99999"
   }
   ```
3. **Unauthorized**:

   json

   ```
   {
     "success": false,
     "message": "Unauthorized"
   }
   ```
4. **Access Denied**:

   json

   ```
   {
     "success": false,
     "message": "Access denied to document"
   }
   ```
5. **Document Locked**:

   json

   ```
   {
     "success": false,
     "message": "Cannot delete locked document"
   }
   ```

***

### **Notes**

* **Permanent Deletion**: Deleted documents cannot be recovered
* **Locked Documents**: Documents with `isLock: true` cannot be deleted
* **Approved Documents**: Consider implications before deleting approved documents
* **Audit Trail**: Deletion may be logged for compliance purposes
* **Permissions**: Ensure proper authorization before deletion

**Restrictions**:

* ❌ Cannot delete locked documents (`isLock: true`)
* ❌ Cannot delete documents that are part of active verification processes
* ❌ Cannot delete documents referenced in pending transactions
* ✅ Can delete documents with status: `SUBMITTED`, `REJECTED`, `CHANGES_REQUESTED`
* ✅ Can delete `APPROVED` documents (with caution)

**Best Practices**:

1. **Verify Before Delete**: Always check document status and metadata before deletion
2. **User Confirmation**: Implement confirmation dialogs in user interfaces
3. **Error Handling**: Handle all possible error responses gracefully
4. **Logging**: Log deletion operations for audit purposes
5. **Backup Consideration**: Ensure important documents are backed up if needed

**Pre-deletion Checklist**:

* Confirm document is not locked
* Verify document is not required for active processes
* Check if document needs to be archived instead of deleted
* Ensure proper user authorization
* Consider compliance and retention requirements


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.delos.financial/documents/delete-document.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
