# API Integration & Core Reference

Welcome to the **AmanDevelops AI API Platform**. Our platform provides a high-performance, asynchronous REST API designed to power AI generation across multiple models and architectures.

---

## 1. Core Architecture & Execution Flow

All heavy compute generation on our platform operates **asynchronously** to ensure immediate HTTP response times, prevent timeouts, and provide predictable queueing:

1. **Submit Generation (`POST /v1/{model}/`):** Your application dispatches a task to the specific model route (e.g., `/v1/eden-v1/`). The API immediately validates your credentials and parameters, queues the job, and responds with `HTTP 202 Accepted` containing a unique `task_id`.
2. **Retrieve Results:** Your application can retrieve results via:
   * **Task Polling (`GET /v1/tasks/{task_id}`):** Query the task endpoint periodically. Polling reads directly from our high-speed database cache and never strains upstream generation workers.
   * **Webhooks (Automated Callbacks):** Supply an optional `webhook_url` in your request. When generation finishes, our system dispatches an HTTP POST callback directly to your server with the output image URL and metadata.

---

## 2. Authentication

All requests to the API require a valid API key. You can pass your key using either the standard HTTP `Authorization` header or the `X-API-Key` header:

### Standard Bearer Header (Recommended)
```http
Authorization: Bearer <YOUR_API_KEY>
```

### Alternative Custom Header
```http
X-API-Key: <YOUR_API_KEY>
```

> [!IMPORTANT]
> **Keep your API key secure.** Always initiate requests from your backend server. Never expose your API key in client-side code (browsers, mobile app client bundles, or public repositories).

---

## 3. Submitting a Generation Request

* **Base URL:** `https://api.amandevelops.com`
* **Method:** `POST`
* **Path:** `/v1/{model}/` (e.g., `/v1/eden-v1/`)
* **Headers:**
  ```http
  Authorization: Bearer <YOUR_API_KEY>
  Content-Type: application/json
  ```

### Request Structure
Each model accepts a JSON body tailored to its specific capabilities (e.g., text-to-image parameters, character definitions, dimensions). Please consult the dedicated documentation page for each specific model (such as [Eden v1 Documentation](docs/?page=eden-v1)) for exact parameter specifications.

Common parameters shared across generation requests include:
* `webhook_url` *(string, optional)*: A publicly accessible HTTPS URL where completion notifications will be sent.
* `seed` *(integer, optional)*: Seed number for reproducible generations (`-1` for random).

### Response: `HTTP 202 Accepted`
When a valid generation request is received, the server enqueues the task immediately:

```json
{
  "status": "success",
  "code": "TASK_QUEUED",
  "message": "Image generation task has been queued successfully.",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "created_at": "2026-09-04T04:00:00Z",
  "webhook_url": "https://yourdomain.com/webhooks/receiver",
  "usage": {
    "execution_time_ms": 115,
    "requests_remaining": 994
  }
}
```

---

## 4. Polling Task Results

Clients can check task status at any time to monitor generation progress or retrieve the final output image URL.

### Endpoint
* **Path:** `GET https://api.amandevelops.com/v1/tasks/{task_id}`
* **Alternative:** `GET https://api.amandevelops.com/v1/tasks/?task_id={task_id}`
* **Headers:**
  ```http
  Authorization: Bearer <YOUR_API_KEY>
  ```

> [!TIP]
> **Pure Database Polling:** Polling reads state directly from our local database index. You can poll safely without worrying about overloading backend GPU generation servers. We recommend polling every 2 to 3 seconds.

### Task Lifecycle States

| State | Status Code | Description | Next Action |
|---|---|---|---|
| `queued` | `TASK_QUEUED` | Task is waiting in queue for an available GPU worker. | Continue polling every 2–3s. |
| `processing` | `TASK_PROCESSING` | Task is actively generating and rendering on the GPU. | Continue polling every 2–3s. |
| `completed` | `TASK_COMPLETED` | Generation finished successfully. The output image is ready. | Fetch `result_url` and cease polling. |
| `failed` | `TASK_FAILED` | Generation failed due to invalid prompt parameters or worker error. | Inspect `error` and cease polling. |

### Polling Responses

#### In Progress (`state: "processing"`)
```json
{
  "status": "success",
  "code": "TASK_PROCESSING",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "state": "processing",
  "message": "Task is actively being generated by the GPU worker.",
  "created_at": "2026-09-04 04:00:00"
}
```

#### Completed — Single Asset (e.g. Eden v1)
```json
{
  "status": "success",
  "code": "TASK_COMPLETED",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "state": "completed",
  "result_url": "https://api.amandevelops.com/storage/eden-v1/img_eden_8b31cf6471e9a25d0c81.png",
  "webhook_status": "delivered",
  "created_at": "2026-09-04 04:00:00",
  "completed_at": "2026-09-04 04:00:14"
}
```

#### Completed — Multi-Asset Output (e.g. IV1)
```json
{
  "status": "success",
  "code": "TASK_COMPLETED",
  "task_id": "task_iv1_9f4e2a8c1b3d7e5a0c6f1234",
  "model": "iv1",
  "state": "completed",
  "outputs": {
    "original_video": "https://api.amandevelops.com/storage/iv1/vid_iv1_9f4e2a8c1b3d_orig.mp4",
    "original_end_frame": "https://api.amandevelops.com/storage/iv1/frame_iv1_9f4e2a8c1b3d_orig.png",
    "upscaled_video": "https://api.amandevelops.com/storage/iv1/vid_iv1_9f4e2a8c1b3d_upscaled.mp4",
    "upscaled_end_frame": "https://api.amandevelops.com/storage/iv1/frame_iv1_9f4e2a8c1b3d_upscaled.png"
  },
  "result_url": "https://api.amandevelops.com/storage/iv1/vid_iv1_9f4e2a8c1b3d_upscaled.mp4",
  "webhook_status": "delivered",
  "created_at": "2026-09-17 03:00:00",
  "completed_at": "2026-09-17 03:02:18"
}
```

#### Failed (`state: "failed"`)
```json
{
  "status": "success",
  "code": "TASK_FAILED",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "state": "failed",
  "error": "Upstream worker failed to generate prompt.",
  "created_at": "2026-09-04 04:00:00",
  "completed_at": "2026-09-04 04:00:06"
}
```

---

## 5. Webhooks & Callback Security

Instead of continuous polling, you can pass a `webhook_url` when creating a task. When the task reaches a terminal state (`completed` or `failed`), our server sends an HTTP POST request to your endpoint.

### Webhook Headers
Every webhook transmission includes tracking headers:
* `Content-Type: application/json`
* `User-Agent: AmanDevelops-Webhook/1.0`
* `X-AmanDevelops-Event: task.completed` (or `task.failed`)
* `X-AmanDevelops-Delivery: <UUIDv4>` (Unique per delivery attempt)

### Completed Payload Example
```json
{
  "event": "task.completed",
  "delivery_id": "7f81b29a-24cd-4e8a-bf90-349f50e7b231",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "status": "completed",
  "result_url": "https://api.amandevelops.com/storage/eden-v1/img_eden_8b31cf6471e9a25d0c81.png",
  "error": null,
  "created_at": "2026-09-04 04:00:00",
  "completed_at": "2026-09-04T04:00:14Z",
  "parameters": {
    "scene": "...",
    "resolution": 1080
  }
}
```

### Failed Payload Example
```json
{
  "event": "task.failed",
  "delivery_id": "0b15da22-1d54-411a-8fba-997645ef01a8",
  "task_id": "task_eden_7f8a9b2c3d4e5f6a",
  "model": "eden-v1",
  "status": "failed",
  "result_url": null,
  "error": "Upstream generation timed out.",
  "created_at": "2026-09-04 04:00:00",
  "completed_at": "2026-09-04T04:00:30Z"
}
```

### Webhook Security & Best Practices
1. **Verify Headers:** Confirm the incoming request contains `User-Agent: AmanDevelops-Webhook/1.0` and a valid `X-AmanDevelops-Event`.
2. **Idempotency:** Always store the `delivery_id` or `task_id` to ensure duplicate deliveries are ignored safely.
3. **Acknowledge Fast (HTTP 200):** Respond with `HTTP 200 OK` within 5 seconds of receiving the callback. Heavy background operations (such as re-encoding or uploading to third-party CDNs) should be offloaded to an asynchronous background worker.
4. **HTTPS Enforcement:** Webhook endpoints must use SSL/TLS (`https://`). Insecure plain HTTP endpoints are rejected.

---

## 6. Implementation Code Examples

### Python (Submit & Poll Pattern)
```python
import time
import requests

API_KEY = "ak_live_your_actual_api_key_here"
BASE_URL = "https://api.amandevelops.com"
MODEL = "eden-v1"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

payload = {
    "scene": "A person reading a book in a cozy library with warm lighting",
    "resolution": 1080,
    "aspect_ratio": "1:1"
}

# 1. Submit Generation Request
response = requests.post(f"{BASE_URL}/v1/{MODEL}/", json=payload, headers=headers)
if response.status_code != 202:
    print(f"Submission Error ({response.status_code}):", response.text)
    exit(1)

task_id = response.json()["task_id"]
print(f"Task queued successfully! ID: {task_id}")

# 2. Poll for Completion
poll_url = f"{BASE_URL}/v1/tasks/{task_id}"
timeout_seconds = 120
start_time = time.time()

while time.time() - start_time < timeout_seconds:
    poll_res = requests.get(poll_url, headers=headers).json()
    state = poll_res.get("state")

    if state == "completed":
        print("Generation Complete! Image URL:", poll_res["result_url"])
        break
    elif state == "failed":
        print("Generation Failed:", poll_res.get("error"))
        break
    else:
        print(f"Status: {state}... waiting 2.5s")
        time.sleep(2.5)
```

### Node.js (Fetch & Polling)
```javascript
const API_KEY = "ak_live_your_actual_api_key_here";
const BASE_URL = "https://api.amandevelops.com";
const MODEL = "eden-v1";

async function runGeneration() {
  const headers = {
    "Authorization": `Bearer ${API_KEY}`,
    "Content-Type": "application/json"
  };

  const payload = {
    scene: "A modern electric vehicle charging at sunset",
    resolution: 1080,
    aspect_ratio: "16:9"
  };

  // 1. Submit generation task
  const submitRes = await fetch(`${BASE_URL}/v1/${MODEL}/`, {
    method: "POST",
    headers,
    body: JSON.stringify(payload)
  });

  if (submitRes.status !== 202) {
    throw new Error(`Submission failed: ${await submitRes.text()}`);
  }

  const { task_id } = await submitRes.json();
  console.log(`Task accepted: ${task_id}`);

  // 2. Poll task status
  const pollUrl = `${BASE_URL}/v1/tasks/${task_id}`;
  const interval = setInterval(async () => {
    try {
      const pollRes = await fetch(pollUrl, { headers });
      const task = await pollRes.json();

      if (task.state === "completed") {
        clearInterval(interval);
        console.log("Image ready:", task.result_url);
      } else if (task.state === "failed") {
        clearInterval(interval);
        console.error("Task failed:", task.error);
      } else {
        console.log(`Current state: ${task.state}...`);
      }
    } catch (err) {
      clearInterval(interval);
      console.error("Polling error:", err);
    }
  }, 2500);
}

runGeneration().catch(console.error);
```

### PHP (Submit & Poll via cURL)
```php
<?php
/**
 * Asynchronous Task Submission & Status Polling in Native PHP
 */

$apiKey = 'ak_live_your_actual_api_key_here';
$baseUrl = 'https://api.amandevelops.com';
$model = 'eden-v1';

$payload = [
    'scene' => 'Zoe smiling naturally in a vibrant summer flower garden',
    'aspect_ratio' => '1:1',
    'resolution' => 1080
];

// 1. Submit Generation Request (POST /v1/{model}/)
$ch = curl_init("{$baseUrl}/v1/{$model}/");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ],
    CURLOPT_TIMEOUT        => 30
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 202) {
    die("Submission failed with HTTP {$httpCode}: {$response}\n");
}

$taskData = json_decode($response, true);
$taskId = $taskData['task_id'] ?? null;
echo "Task queued successfully! Task ID: {$taskId}\n";

// 2. Poll for Completion (GET /v1/tasks/{task_id})
$pollUrl = "{$baseUrl}/v1/tasks/" . urlencode($taskId);
$maxAttempts = 40;
$attempt = 0;

while ($attempt < $maxAttempts) {
    $attempt++;
    sleep(3);

    $ch = curl_init($pollUrl);
    curl_setopt_array($ch, [
        CURLOPT_HTTPGET        => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_TIMEOUT        => 15
    ]);

    $pollResponse = curl_exec($ch);
    curl_close($ch);

    $pollData = json_decode($pollResponse, true);
    $state = $pollData['state'] ?? 'unknown';

    if ($state === 'completed') {
        echo "Generation Complete!\n";
        echo "Result URL: " . (is_array($pollData['result_url']) ? json_encode($pollData['result_url']) : $pollData['result_url']) . "\n";
        break;
    } elseif ($state === 'failed') {
        echo "Generation Failed: " . ($pollData['error'] ?? 'Unknown error') . "\n";
        break;
    } else {
        echo "Status: " . strtoupper($state) . "... waiting 3s (Attempt {$attempt})\n";
    }
}
?>
```

---

### PHP (Webhook Receiver Endpoint)
```php
<?php
/**
 * Webhook Receiver Callback Endpoint
 * Deploy at: https://yourdomain.com/webhook-receiver.php
 */
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);

$event = $_SERVER['HTTP_X_AMANDEVELOPS_EVENT'] ?? '';
$deliveryId = $_SERVER['HTTP_X_AMANDEVELOPS_DELIVERY'] ?? '';

if (!is_array($data) || empty($deliveryId)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid Webhook Payload']);
    exit;
}

$taskId = $data['task_id'] ?? '';
$status = $data['status'] ?? '';

if ($status === 'completed') {
    $resultUrl = $data['result_url'] ?? '';
    // Store result URL or update database record here
} elseif ($status === 'failed') {
    $error = $data['error'] ?? 'Unknown failure';
    // Record task failure
}

// Acknowledge receipt immediately with HTTP 200
http_response_code(200);
echo json_encode(['received' => true, 'task_id' => $taskId]);
exit;
```

---

### Python (Webhook Receiver with Flask)
```python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/webhooks/amandevelops", methods=["POST"])
def webhook_receiver():
    event_type = request.headers.get("X-AmanDevelops-Event")
    delivery_id = request.headers.get("X-AmanDevelops-Delivery")
    data = request.get_json()

    print(f"Received Webhook [{event_type}] Delivery ID: {delivery_id}")

    if data.get("status") == "completed":
        task_id = data["task_id"]
        result_url = data["result_url"]
        print(f"Task {task_id} completed! Asset: {result_url}")
        # Process output asset, notify user, or persist to DB
    elif data.get("status") == "failed":
        print(f"Task {data.get('task_id')} failed: {data.get('error')}")

    # Acknowledge receipt immediately with HTTP 200
    return jsonify({"received": True}), 200

if __name__ == "__main__":
    app.run(port=5000)
```

---

## 7. HTTP Status & Error Codes

| HTTP Status | Error Code | Description |
|---|---|---|
| `200 OK` | `TASK_COMPLETED` / `TASK_PROCESSING` | Successful task retrieval response. |
| `202 Accepted` | `TASK_QUEUED` | Task accepted and queued for GPU processing. |
| `400 Bad Request` | `INVALID_PAYLOAD` / `MISSING_SCENE` | Request body is missing required parameters or malformed JSON. |
| `401 Unauthorized` | `INVALID_API_KEY` | Missing, incorrect, or inactive API key. |
| `403 Forbidden` | `ACCOUNT_DISABLED` / `DAILY_LIMIT_REACHED` | Account status disabled or daily/weekly limit reached. |
| `404 Not Found` | `TASK_NOT_FOUND` | No task matches the specified `task_id`. |
| `405 Method Not Allowed`| `METHOD_NOT_ALLOWED` | Wrong HTTP verb used (e.g. GET on generation endpoint). |
| `429 Too Many Requests`| `RATE_LIMIT_EXCEEDED` | Request rate limit exceeded. Retry with backoff. |
| `502 Bad Gateway` | `UPSTREAM_ERROR` | Upstream generation backend temporarily unavailable. |