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

# List Tasks

> Retrieve a paginated list of tasks with optional filtering by date range

## Endpoint

```
GET /api/v1/tasks
```

## Authentication

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

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

## Query Parameters

<ParamField query="page" type="integer">
  Page number for pagination (1-indexed). If provided, `limit` is required.
</ParamField>

<ParamField query="limit" type="integer">
  Number of tasks to return per page. Required when `page` is provided.
</ParamField>

<ParamField query="start" type="string">
  Start date for filtering tasks (ISO 8601 format). Only tasks created on or after this date will be returned.
</ParamField>

<ParamField query="end" type="string">
  End date for filtering tasks (ISO 8601 format). Only tasks created on or before this date will be returned.
</ParamField>

<ParamField query="base64_urls" type="boolean" default={false}>
  Whether to return base64 encoded URLs. If false, URLs will be returned as presigned URLs.
</ParamField>

<ParamField query="include_chunks" type="boolean" default={false}>
  Whether to include chunks in the output response for each task. Set to true to get full task details (can increase response size significantly).
</ParamField>

## Response

Returns an array of task objects. Each task has the same structure as the [Get Task](/api/tasks/get) response.

<ResponseField name="tasks" type="array">
  Array of task objects, each containing:

  <Expandable title="properties">
    <ResponseField name="task_id" type="string">
      Unique identifier for the task
    </ResponseField>

    <ResponseField name="status" type="enum">
      Task status: `Starting`, `Processing`, `Succeeded`, `Failed`, or `Cancelled`
    </ResponseField>

    <ResponseField name="created_at" type="string">
      Creation timestamp (ISO 8601)
    </ResponseField>

    <ResponseField name="started_at" type="string">
      Processing start timestamp (ISO 8601)
    </ResponseField>

    <ResponseField name="finished_at" type="string">
      Completion timestamp (ISO 8601)
    </ResponseField>

    <ResponseField name="expires_at" type="string">
      Expiration timestamp (ISO 8601)
    </ResponseField>

    <ResponseField name="message" type="string">
      Status message or error description
    </ResponseField>

    <ResponseField name="task_url" type="string">
      Presigned URL of the task
    </ResponseField>

    <ResponseField name="configuration" type="object">
      Complete task configuration including input file URL and all processing settings
    </ResponseField>

    <ResponseField name="output" type="object">
      Output data (only included if `include_chunks=true` and status is `Succeeded`)
    </ResponseField>
  </Expandable>
</ResponseField>

## Status Codes

* **200**: Tasks retrieved successfully
* **400**: Bad request (limit is required when page is provided)
* **500**: Internal server error

## Examples

<CodeGroup>
  ```bash cURL (Basic) theme={null}
  curl -X GET "https://api.chunkr.ai/api/v1/tasks" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (Paginated) theme={null}
  curl -X GET "https://api.chunkr.ai/api/v1/tasks?page=1&limit=10" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (Date Filter) theme={null}
  curl -X GET "https://api.chunkr.ai/api/v1/tasks?start=2024-01-01T00:00:00Z&end=2024-12-31T23:59:59Z" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```bash cURL (With Chunks) theme={null}
  curl -X GET "https://api.chunkr.ai/api/v1/tasks?page=1&limit=5&include_chunks=true" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

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

  url = "https://api.chunkr.ai/api/v1/tasks"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY"
  }

  # Get first page of tasks
  params = {
      "page": 1,
      "limit": 10,
      "include_chunks": False
  }

  response = requests.get(url, headers=headers, params=params)
  tasks = response.json()

  print(f"Retrieved {len(tasks)} tasks")
  for task in tasks:
      print(f"Task {task['task_id']}: {task['status']}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.chunkr.ai/api/v1/tasks?page=1&limit=10',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const tasks = await response.json();
  console.log(`Retrieved ${tasks.length} tasks`);

  tasks.forEach(task => {
    console.log(`Task ${task.task_id}: ${task.status}`);
  });
  ```

  ```python Python (Date Range) theme={null}
  import requests
  from datetime import datetime, timedelta

  url = "https://api.chunkr.ai/api/v1/tasks"
  headers = {"Authorization": "Bearer YOUR_API_KEY"}

  # Get tasks from the last 7 days
  end = datetime.utcnow()
  start = end - timedelta(days=7)

  params = {
      "start": start.isoformat() + "Z",
      "end": end.isoformat() + "Z",
      "page": 1,
      "limit": 50
  }

  response = requests.get(url, headers=headers, params=params)
  tasks = response.json()

  print(f"Tasks in last 7 days: {len(tasks)}")

  # Count by status
  status_counts = {}
  for task in tasks:
      status = task['status']
      status_counts[status] = status_counts.get(status, 0) + 1

  print("Status breakdown:")
  for status, count in status_counts.items():
      print(f"  {status}: {count}")
  ```

  ```python Python (Paginate All) theme={null}
  import requests

  def get_all_tasks(api_key, limit=100):
      """Fetch all tasks using pagination"""
      url = "https://api.chunkr.ai/api/v1/tasks"
      headers = {"Authorization": f"Bearer {api_key}"}
      
      all_tasks = []
      page = 1
      
      while True:
          params = {"page": page, "limit": limit}
          response = requests.get(url, headers=headers, params=params)
          
          if response.status_code != 200:
              break
          
          tasks = response.json()
          if not tasks:
              break
          
          all_tasks.extend(tasks)
          print(f"Fetched page {page}: {len(tasks)} tasks")
          
          # If we got fewer tasks than the limit, we've reached the end
          if len(tasks) < limit:
              break
          
          page += 1
      
      return all_tasks

  tasks = get_all_tasks("YOUR_API_KEY")
  print(f"Total tasks: {len(tasks)}")
  ```
</CodeGroup>

## Filtering and Pagination

### Date Range Filtering

Filter tasks by creation date using `start` and `end` parameters:

```python theme={null}
# Last 24 hours
params = {
    "start": (datetime.utcnow() - timedelta(days=1)).isoformat() + "Z",
    "end": datetime.utcnow().isoformat() + "Z"
}

# Specific month
params = {
    "start": "2024-03-01T00:00:00Z",
    "end": "2024-03-31T23:59:59Z"
}
```

### Pagination

When using pagination:

* Pages are 1-indexed (first page is `page=1`)
* `limit` is **required** when `page` is specified
* If a page has fewer items than `limit`, you've reached the last page
* Without `page` and `limit`, all tasks are returned (use with caution for large datasets)

## Performance Considerations

1. **include\_chunks**: Setting this to `true` significantly increases response size and processing time. Only use when you need full task details.

2. **Pagination**: Always use pagination for large result sets to avoid timeouts and memory issues.

3. **Date Filtering**: Narrow your date range to improve query performance.

4. **Limit Size**: Recommended limit values:
   * Small limit (10-50): For UI pagination
   * Medium limit (50-100): For data processing
   * Large limit (100+): Only when necessary and with pagination

## Common Use Cases

### Monitor Recent Tasks

```python theme={null}
# Get tasks from the last hour
params = {
    "start": (datetime.utcnow() - timedelta(hours=1)).isoformat() + "Z",
    "limit": 100
}
```

### Find Failed Tasks

```python theme={null}
tasks = requests.get(url, headers=headers).json()
failed = [t for t in tasks if t['status'] == 'Failed']
print(f"Failed tasks: {len(failed)}")
```

### Export Task Summary

```python theme={null}
import csv

tasks = get_all_tasks(api_key)

with open('tasks.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Task ID', 'Status', 'Created', 'Finished'])
    
    for task in tasks:
        writer.writerow([
            task['task_id'],
            task['status'],
            task['created_at'],
            task.get('finished_at', 'N/A')
        ])
```

### Cleanup Old Tasks

```python theme={null}
# Find and delete tasks older than 30 days
old_date = (datetime.utcnow() - timedelta(days=30)).isoformat() + "Z"

params = {"end": old_date}
tasks = requests.get(url, headers=headers, params=params).json()

for task in tasks:
    if task['status'] in ['Succeeded', 'Failed', 'Cancelled']:
        delete_url = f"https://api.chunkr.ai/api/v1/task/{task['task_id']}"
        requests.delete(delete_url, headers=headers)
        print(f"Deleted task {task['task_id']}")
```

## Error Handling

```python theme={null}
import requests

def list_tasks_safe(api_key, page=None, limit=None):
    """List tasks with proper error handling"""
    url = "https://api.chunkr.ai/api/v1/tasks"
    headers = {"Authorization": f"Bearer {api_key}"}
    
    params = {}
    if page is not None:
        if limit is None:
            return {"error": "limit is required when page is provided"}
        params["page"] = page
        params["limit"] = limit
    
    try:
        response = requests.get(url, headers=headers, params=params, timeout=30)
        
        if response.status_code == 200:
            return {"success": True, "tasks": response.json()}
        elif response.status_code == 400:
            return {"error": response.text}
        else:
            return {"error": f"HTTP {response.status_code}: {response.text}"}
            
    except requests.exceptions.Timeout:
        return {"error": "Request timed out"}
    except requests.exceptions.RequestException as e:
        return {"error": f"Network error: {str(e)}"}
```

## Related Endpoints

* [Get Task](/api/tasks/get) - Get detailed information about a specific task
* [Create Task](/api/tasks/create) - Create a new task
* [Delete Task](/api/tasks/delete) - Delete tasks from the list
