> ## Documentation Index
> Fetch the complete documentation index at: https://docs.daycopilot.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Your First API Call

> Comprehensive guide to making your first successful API request to Day Copilot

## Overview

This guide walks you through making your first API call to Day Copilot, from obtaining credentials to handling the response. By the end, you'll have created your first task via the API.

<Note>
  Estimated time: 10 minutes
</Note>

## Prerequisites

Before you begin, you need:

1. A Day Copilot account - [Sign up here](https://app.daycopilot.ai/signup)
2. An HTTP client:
   * **Command line:** cURL (built into Mac/Linux, [Windows download](https://curl.se/windows/))
   * **GUI:** [Postman](https://www.postman.com/downloads/) or [Insomnia](https://insomnia.rest/download)
   * **Code:** Your preferred programming language

## Step 1: Get Your Authentication Token

### Via Dashboard

1. Log in to [Day Copilot](https://app.daycopilot.ai)
2. Navigate to **Settings** → **API Tokens**
3. Click **Generate New Token**
4. Copy the token (it will only be shown once!)

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLXV1aWQifQ...
```

<Warning>
  **Keep your token secret!** Never commit it to version control or share it publicly. Treat it like a password.
</Warning>

### Store Your Token Securely

<CodeGroup>
  ```bash Terminal theme={null}
  # Set as environment variable
  export DAY_COPILOT_TOKEN="your-token-here"
  ```

  ```javascript .env File theme={null}
  # Create .env file
  DAY_COPILOT_TOKEN=your-token-here

  # Add to .gitignore
  echo ".env" >> .gitignore
  ```
</CodeGroup>

## Step 2: Make Your First Request

Let's fetch your existing tasks to verify authentication works.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://app.daycopilot.ai/api/v1/tasks" \
    -H "Authorization: Bearer $DAY_COPILOT_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```javascript Node.js theme={null}
  const TOKEN = process.env.DAY_COPILOT_TOKEN;

  const response = await fetch('https://app.daycopilot.ai/api/v1/tasks', {
    headers: {
      'Authorization': `Bearer ${TOKEN}`,
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  console.log('Tasks:', data);
  ```

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

  TOKEN = os.getenv('DAY_COPILOT_TOKEN')

  response = requests.get(
      'https://app.daycopilot.ai/api/v1/tasks',
      headers={
          'Authorization': f'Bearer {TOKEN}',
          'Content-Type': 'application/json'
      }
  )

  data = response.json()
  print('Tasks:', data)
  ```
</CodeGroup>

### Expected Response

```json theme={null}
{
  "data": [],
  "meta": {
    "pagination": {
      "limit": 50,
      "offset": 0,
      "total": 0,
      "hasMore": false
    }
  }
}
```

<Tip>
  If you get an empty array, that's perfect! It means authentication worked and you just don't have any tasks yet.
</Tip>

## Step 3: Create Your First Task

Now let's create a task:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://app.daycopilot.ai/api/v1/tasks" \
    -H "Authorization: Bearer $DAY_COPILOT_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "title": "My First API Task",
      "description": "Created using the Day Copilot API",
      "priority": "medium",
      "status": "pending"
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://app.daycopilot.ai/api/v1/tasks', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'My First API Task',
      description: 'Created using the Day Copilot API',
      priority: 'medium',
      status: 'pending'
    })
  });

  const task = await response.json();
  console.log('Created task:', task);
  ```

  ```python Python theme={null}
  response = requests.post(
      'https://app.daycopilot.ai/api/v1/tasks',
      headers={
          'Authorization': f'Bearer {TOKEN}',
          'Content-Type': 'application/json'
      },
      json={
          'title': 'My First API Task',
          'description': 'Created using the Day Copilot API',
          'priority': 'medium',
          'status': 'pending'
      }
  )

  task = response.json()
  print('Created task:', task)
  ```
</CodeGroup>

### Success Response

```json theme={null}
{
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "title": "My First API Task",
    "description": "Created using the Day Copilot API",
    "priority": "medium",
    "status": "pending",
    "created_at": "2025-11-02T12:00:00Z",
    "updated_at": "2025-11-02T12:00:00Z",
    "user_id": "your-user-uuid",
    "version_major": 1,
    "version_minor": 0,
    "is_published": true
  }
}
```

**Key Fields:**

* `id`: Unique identifier for this task
* `created_at`: ISO 8601 timestamp
* `version_major/minor`: Versioning info
* `is_published`: Whether task is published (new tasks are auto-published)

## Step 4: Retrieve Your Task

Use the `id` from the creation response to fetch your task:

<CodeGroup>
  ```bash cURL theme={null}
  # Replace {taskId} with actual ID from previous step
  curl -X GET "https://app.daycopilot.ai/api/v1/tasks/{taskId}" \
    -H "Authorization: Bearer $DAY_COPILOT_TOKEN"
  ```

  ```javascript Node.js theme={null}
  const taskId = '550e8400-e29b-41d4-a716-446655440000';

  const response = await fetch(`https://app.daycopilot.ai/api/v1/tasks/${taskId}`, {
    headers: {
      'Authorization': `Bearer ${TOKEN}`
    }
  });

  const task = await response.json();
  console.log('Retrieved task:', task);
  ```

  ```python Python theme={null}
  task_id = '550e8400-e29b-41d4-a716-446655440000'

  response = requests.get(
      f'https://app.daycopilot.ai/api/v1/tasks/{task_id}',
      headers={'Authorization': f'Bearer {TOKEN}'}
  )

  task = response.json()
  print('Retrieved task:', task)
  ```
</CodeGroup>

## Step 5: Update Your Task

Let's change the priority to high:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PUT "https://app.daycopilot.ai/api/v1/tasks/{taskId}" \
    -H "Authorization: Bearer $DAY_COPILOT_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "priority": "high"
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(`https://app.daycopilot.ai/api/v1/tasks/${taskId}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      priority: 'high'
    })
  });

  const updated = await response.json();
  console.log('Updated task:', updated);
  ```

  ```python Python theme={null}
  response = requests.put(
      f'https://app.daycopilot.ai/api/v1/tasks/{task_id}',
      headers={
          'Authorization': f'Bearer {TOKEN}',
          'Content-Type': 'application/json'
      },
      json={'priority': 'high'}
  )

  updated = response.json()
  print('Updated task:', updated)
  ```
</CodeGroup>

## Step 6: Complete Your Task

Mark the task as completed:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://app.daycopilot.ai/api/v1/tasks/{taskId}/complete" \
    -H "Authorization: Bearer $DAY_COPILOT_TOKEN"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch(`https://app.daycopilot.ai/api/v1/tasks/${taskId}/complete`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${TOKEN}`
    }
  });

  const completed = await response.json();
  console.log('Completed task:', completed);
  ```

  ```python Python theme={null}
  response = requests.post(
      f'https://app.daycopilot.ai/api/v1/tasks/{task_id}/complete',
      headers={'Authorization': f'Bearer {TOKEN}'}
  )

  completed = response.json()
  print('Completed task:', completed)
  ```
</CodeGroup>

## Common Errors & Solutions

### 401 Unauthorized

```json theme={null}
{
  "error": "Unauthorized",
  "message": "Missing or invalid authentication token",
  "status": 401
}
```

**Solutions:**

* Check token is valid (not expired)
* Verify `Authorization: Bearer TOKEN` format
* Ensure token has no extra whitespace

### 404 Not Found

```json theme={null}
{
  "error": "Not Found",
  "message": "Task with ID abc-123 does not exist",
  "status": 404
}
```

**Solutions:**

* Verify task ID is correct
* Check task wasn't deleted
* Confirm you have access to this task (RLS)

### 429 Rate Limited

```json theme={null}
{
  "error": "Rate limit exceeded",
  "message": "Too many requests",
  "status": 429,
  "retryAfter": 60
}
```

**Solutions:**

* Wait `retryAfter` seconds before retry
* Implement exponential backoff
* Review [rate limits](/rate-limits)

## Next Steps: Full CRUD Example

Here's a complete script demonstrating all operations:

<CodeGroup>
  ```javascript Node.js theme={null}
  const TOKEN = process.env.DAY_COPILOT_TOKEN;
  const BASE_URL = 'https://app.daycopilot.ai/api/v1';

  async function makeRequest(method, endpoint, body = null) {
    const options = {
      method,
      headers: {
        'Authorization': `Bearer ${TOKEN}`,
        'Content-Type': 'application/json'
      }
    };

    if (body) {
      options.body = JSON.stringify(body);
    }

    const response = await fetch(`${BASE_URL}${endpoint}`, options);

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error: ${error.message}`);
    }

    return response.json();
  }

  async function main() {
    try {
      // Create
      console.log('Creating task...');
      const created = await makeRequest('POST', '/tasks', {
        title: 'Learn Day Copilot API',
        priority: 'high'
      });
      const taskId = created.data.id;
      console.log('✓ Created:', taskId);

      // Read
      console.log('\nReading task...');
      const task = await makeRequest('GET', `/tasks/${taskId}`);
      console.log('✓ Retrieved:', task.data.title);

      // Update
      console.log('\nUpdating task...');
      await makeRequest('PUT', `/tasks/${taskId}`, {
        status: 'in_progress'
      });
      console.log('✓ Updated to in_progress');

      // Complete
      console.log('\nCompleting task...');
      await makeRequest('POST', `/tasks/${taskId}/complete`);
      console.log('✓ Completed');

      // Delete
      console.log('\nDeleting task...');
      await makeRequest('DELETE', `/tasks/${taskId}`);
      console.log('✓ Deleted');

    } catch (error) {
      console.error('Error:', error.message);
    }
  }

  main();
  ```

  ```python Python theme={null}
  import os
  import requests
  from typing import Optional, Dict, Any

  TOKEN = os.getenv('DAY_COPILOT_TOKEN')
  BASE_URL = 'https://app.daycopilot.ai/api/v1'

  def make_request(
      method: str,
      endpoint: str,
      body: Optional[Dict[str, Any]] = None
  ) -> Dict[str, Any]:
      """Make API request with error handling"""
      headers = {
          'Authorization': f'Bearer {TOKEN}',
          'Content-Type': 'application/json'
      }

      response = requests.request(
          method,
          f'{BASE_URL}{endpoint}',
          headers=headers,
          json=body
      )

      if not response.ok:
          error = response.json()
          raise Exception(f"API Error: {error.get('message')}")

      return response.json()

  def main():
      try:
          # Create
          print('Creating task...')
          created = make_request('POST', '/tasks', {
              'title': 'Learn Day Copilot API',
              'priority': 'high'
          })
          task_id = created['data']['id']
          print(f'✓ Created: {task_id}')

          # Read
          print('\nReading task...')
          task = make_request('GET', f'/tasks/{task_id}')
          print(f"✓ Retrieved: {task['data']['title']}")

          # Update
          print('\nUpdating task...')
          make_request('PUT', f'/tasks/{task_id}', {
              'status': 'in_progress'
          })
          print('✓ Updated to in_progress')

          # Complete
          print('\nCompleting task...')
          make_request('POST', f'/tasks/{task_id}/complete')
          print('✓ Completed')

          # Delete
          print('\nDeleting task...')
          make_request('DELETE', f'/tasks/{task_id}')
          print('✓ Deleted')

      except Exception as error:
          print(f'Error: {error}')

  if __name__ == '__main__':
      main()
  ```
</CodeGroup>

## Testing in Postman

1. **Import Collection**: [Download Day Copilot Postman Collection](#)
2. **Set Environment Variable**:
   * Key: `DAY_COPILOT_TOKEN`
   * Value: Your token
3. **Run Requests**: Try each endpoint in the collection

## Congratulations! 🎉

You've successfully:

* ✅ Authenticated with Day Copilot API
* ✅ Created a task
* ✅ Retrieved task data
* ✅ Updated a task
* ✅ Completed a task

## What's Next?

<CardGroup cols={2}>
  <Card title="Managing Tasks" icon="list-check" href="/guides/managing-tasks">
    Learn advanced task management techniques
  </Card>

  <Card title="Working with Events" icon="calendar" href="/guides/working-with-events">
    Create and manage calendar events
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/guides/error-handling">
    Handle errors gracefully in production
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>
</CardGroup>
