> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/lumina-ai-inc/chunkr/llms.txt
> Use this file to discover all available pages before exploring further.

# Delete Task

> Permanently delete a task and all associated data

## Endpoint

```
DELETE /api/v1/task/{task_id}
```

## Authentication

This endpoint requires API key authentication via the `Authorization` header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Path Parameters

<ParamField path="task_id" type="string" required>
  The unique identifier of the task to delete
</ParamField>

## Requirements

* Task must have status `Succeeded`, `Failed`, or `Cancelled`
* Tasks that are `Starting` or `Processing` cannot be deleted (use [Cancel Task](/api/tasks/cancel) instead)

## Response

On success, returns a plain text response:

```
Task deleted
```

## Status Codes

* **200**: Task deleted successfully
* **400**: Bad request (task cannot be deleted due to invalid status)
* **404**: Task not found or expired
* **500**: Internal server error

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X DELETE "https://api.chunkr.ai/api/v1/task/123e4567-e89b-12d3-a456-426614174000" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```python Python theme={null}
  import requests

  task_id = "123e4567-e89b-12d3-a456-426614174000"
  url = f"https://api.chunkr.ai/api/v1/task/{task_id}"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY"
  }

  response = requests.delete(url, headers=headers)

  if response.status_code == 200:
      print("Task deleted successfully")
  else:
      print(f"Error: {response.text}")
  ```

  ```javascript JavaScript theme={null}
  const taskId = '123e4567-e89b-12d3-a456-426614174000';
  const response = await fetch(
    `https://api.chunkr.ai/api/v1/task/${taskId}`,
    {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  if (response.ok) {
    console.log('Task deleted successfully');
  } else {
    const error = await response.text();
    console.error('Error:', error);
  }
  ```

  ```python Python (Safe Delete) theme={null}
  import requests

  def safe_delete_task(task_id, api_key):
      """Delete a task only if it's in a deletable state"""
      # First, check the task status
      get_url = f"https://api.chunkr.ai/api/v1/task/{task_id}"
      headers = {"Authorization": f"Bearer {api_key}"}
      
      get_response = requests.get(get_url, headers=headers)
      if get_response.status_code != 200:
          return {"error": "Task not found"}
      
      task = get_response.json()
      status = task['status']
      
      # Check if task can be deleted
      if status not in ['Succeeded', 'Failed', 'Cancelled']:
          return {
              "error": f"Cannot delete task with status '{status}'",
              "suggestion": "Cancel the task first if it's Starting or Processing"
          }
      
      # Delete the task
      delete_response = requests.delete(get_url, headers=headers)
      
      if delete_response.status_code == 200:
          return {"success": True, "message": "Task deleted successfully"}
      else:
          return {"error": delete_response.text}

  result = safe_delete_task("123e4567-e89b-12d3-a456-426614174000", "YOUR_API_KEY")
  print(result)
  ```
</CodeGroup>

## What Gets Deleted

When you delete a task, the following data is permanently removed:

1. **Task Metadata** - All task information from the database
2. **Input File** - The original uploaded file
3. **Processed PDF** - The generated PDF (if applicable)
4. **Output JSON** - All processed chunks and segments
5. **Images** - All cropped segment images and page images
6. **Configuration** - All processing settings

This action is **irreversible** - once deleted, the task and all associated data cannot be recovered.

## Common Use Cases

* **Cleanup**: Remove old or unnecessary tasks to free up storage
* **Privacy**: Delete sensitive documents after processing
* **Testing**: Clean up test tasks during development
* **Error Recovery**: Remove failed tasks that won't be retried

## Best Practices

1. **Download First**: If you need the output data, retrieve it via [GET /task/{task_id}](/api/tasks/get) before deleting

2. **Check Status**: Verify the task is in a deletable state (`Succeeded`, `Failed`, or `Cancelled`)

3. **Batch Operations**: If deleting multiple tasks, implement rate limiting to avoid overwhelming the API

4. **Expiration Alternative**: Consider using the `expires_in` parameter when creating tasks instead of manual deletion

## Error Handling

```python theme={null}
import requests
from requests.exceptions import RequestException

def delete_task_with_retry(task_id, api_key, max_retries=3):
    """Delete task with retry logic"""
    url = f"https://api.chunkr.ai/api/v1/task/{task_id}"
    headers = {"Authorization": f"Bearer {api_key}"}
    
    for attempt in range(max_retries):
        try:
            response = requests.delete(url, headers=headers, timeout=10)
            
            if response.status_code == 200:
                return {"success": True}
            elif response.status_code == 404:
                return {"error": "Task not found or already deleted"}
            elif response.status_code == 400:
                return {"error": response.text}
            else:
                # Retry on 5xx errors
                if attempt < max_retries - 1:
                    continue
                return {"error": f"Failed after {max_retries} attempts"}
                
        except RequestException as e:
            if attempt < max_retries - 1:
                continue
            return {"error": f"Network error: {str(e)}"}
    
    return {"error": "Max retries exceeded"}
```

## Related Endpoints

* [Cancel Task](/api/tasks/cancel) - Cancel a task that is `Starting` or `Processing`
* [Get Task](/api/tasks/get) - Retrieve task data before deletion
* [List Tasks](/api/tasks/list) - Find tasks to delete
