> ## 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.

# Cancel Task

> Cancel a task that hasn't started processing yet

## Endpoint

```
GET /api/v1/task/{task_id}/cancel
```

## 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 cancel
</ParamField>

## Requirements

* Task must have status `Starting`
* Tasks that are already `Processing`, `Succeeded`, `Failed`, or `Cancelled` cannot be cancelled

## Response

On success, returns a plain text response:

```
Task cancelled
```

## Status Codes

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

## Behavior

Depending on the task state:

* **For new tasks**: Status will be updated to `Cancelled` and processing will never begin
* **For updating tasks**: Task will revert to its previous state before the update was requested

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.chunkr.ai/api/v1/task/123e4567-e89b-12d3-a456-426614174000/cancel" \
    -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}/cancel"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY"
  }

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

  if response.status_code == 200:
      print("Task cancelled 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}/cancel`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

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

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

  def safe_cancel_task(task_id, api_key):
      """Cancel a task only if it's in Starting 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 cancelled
      if status != 'Starting':
          return {
              "error": f"Cannot cancel task with status '{status}'",
              "current_status": status,
              "can_cancel": False
          }
      
      # Cancel the task
      cancel_url = f"https://api.chunkr.ai/api/v1/task/{task_id}/cancel"
      cancel_response = requests.get(cancel_url, headers=headers)
      
      if cancel_response.status_code == 200:
          return {"success": True, "message": "Task cancelled successfully"}
      else:
          return {"error": cancel_response.text}

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

## Use Cases

1. **Accidental Submissions**: Cancel tasks that were created by mistake
2. **Configuration Errors**: Cancel and recreate tasks with corrected settings
3. **Queue Management**: Cancel low-priority tasks during high-load periods
4. **Testing**: Cancel test tasks that are no longer needed

## Timing Window

Tasks can only be cancelled while they're in the `Starting` state, which is typically:

* Right after task creation
* Before worker processes pick up the task
* During the queue waiting period

Once a task moves to `Processing` state, it cannot be cancelled and must complete or fail naturally.

## After Cancellation

Once a task is cancelled:

1. **Status** changes to `Cancelled`
2. **Message** is updated to "Task cancelled"
3. Task will **never** begin processing
4. Task can be [deleted](/api/tasks/delete) to free up resources
5. Task **cannot** be restarted - you must create a new task instead

## Error Messages

<ResponseField name="Task not found">
  The task ID doesn't exist, has expired, or you don't have access to it
</ResponseField>

<ResponseField name="Task cannot be cancelled">
  The task is not in `Starting` state. Common reasons:

  * Task is already `Processing`
  * Task has `Succeeded` or `Failed`
  * Task was already `Cancelled`
</ResponseField>

## Best Practices

1. **Check Status First**: Verify the task is in `Starting` state before attempting to cancel

2. **Quick Action**: Cancel as soon as you realize the task is not needed, as tasks may move to `Processing` quickly

3. **Create New Tasks**: After cancelling, create a new task with correct settings rather than trying to uncancelled

4. **Clean Up**: Consider deleting cancelled tasks to keep your task list clean

## Advanced Example: Cancel and Recreate

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

def cancel_and_recreate_task(task_id, new_config, api_key, max_wait=5):
    """Cancel existing task and create a new one with updated config"""
    base_url = "https://api.chunkr.ai/api/v1"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    # Get current task to retrieve original file
    task_response = requests.get(f"{base_url}/task/{task_id}", headers=headers)
    if task_response.status_code != 200:
        return {"error": "Could not retrieve task"}
    
    task = task_response.json()
    
    # Only cancel if in Starting state
    if task['status'] == 'Starting':
        cancel_response = requests.get(
            f"{base_url}/task/{task_id}/cancel",
            headers=headers
        )
        if cancel_response.status_code != 200:
            return {"error": f"Could not cancel: {cancel_response.text}"}
        
        # Wait a moment for cancellation to process
        time.sleep(0.5)
    
    # Create new task with updated configuration
    create_response = requests.post(
        f"{base_url}/task/parse",
        json=new_config,
        headers=headers
    )
    
    if create_response.status_code == 200:
        new_task = create_response.json()
        return {
            "success": True,
            "old_task_id": task_id,
            "new_task_id": new_task['task_id'],
            "message": "Task cancelled and recreated"
        }
    else:
        return {"error": f"Could not create new task: {create_response.text}"}

# Example usage
new_config = {
    "file": "https://example.com/document.pdf",
    "ocr_strategy": "Auto",
    "chunk_processing": {
        "target_length": 1024
    }
}

result = cancel_and_recreate_task(
    "123e4567-e89b-12d3-a456-426614174000",
    new_config,
    "YOUR_API_KEY"
)
print(result)
```

## Related Endpoints

* [Delete Task](/api/tasks/delete) - Permanently delete a `Succeeded`, `Failed`, or `Cancelled` task
* [Get Task](/api/tasks/get) - Check task status before cancelling
* [Create Task](/api/tasks/create) - Create a new task to replace the cancelled one
