# Media quote, upload, and task recovery

## Prepare a reference file

For a filename-only temporary upload, see [Uploading assets](/docs/uploads).

1. Send `POST /api/v1/assets` with `fileName`, `contentType`, and `fileSize` in bytes. The ticket contains a signed `uploadUrl` and a relative `completeUrl`.
2. PUT the raw file bytes to `uploadUrl` with the exact returned Content-Type. Send the API key only to i2v.ai. The signed storage URL already authorizes the PUT.
3. POST to `completeUrl` on the API origin with your Bearer key. Use the verified `url` in the model's reference field. If completion returns `asset_not_ready`, check the uploaded size and type before retrying. The upload ticket expires in 15 minutes.

## Quote and submit with Node.js

Set `I2V_API_KEY`. To include a reference image, set `REFERENCE_IMAGE_PATH` to a local PNG or `REFERENCE_IMAGE_URL` to an existing image URL. The example only quotes until you set both `I2V_MAX_COST_USD` and `I2V_IDEMPOTENCY_KEY`. Set `I2V_RECEIPT_PATH` to an unused, protected local file path before submitting. The example saves the exact body and key there with owner-only permissions. To recover after a timeout, use the receipt lookup below first.

```js
import { readFile, writeFile } from 'node:fs/promises';
import { basename } from 'node:path';

const origin = 'https://api.i2v.ai';
const key = process.env.I2V_API_KEY;
if (!key) throw new Error('Set I2V_API_KEY');

const headers = { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json' };

async function post(path, body, extraHeaders = {}) {
  const response = await fetch(origin + path, {
    method: 'POST',
    headers: { ...headers, ...extraHeaders },
    body: typeof body === 'string' ? body : JSON.stringify(body),
    redirect: 'error',
    signal: AbortSignal.timeout(20_000),
  });
  const result = await response.json();
  if (!response.ok) {
    const requestId = response.headers.get('X-Request-ID') ?? 'unavailable';
    throw new Error(`API error ${response.status} (request ID: ${requestId})`);
  }
  return result;
}

const inputs = { prompt: 'A slow camera push towards the ceramic cup' };
let referenceUrl = process.env.REFERENCE_IMAGE_URL;
if (process.env.REFERENCE_IMAGE_PATH) {
  const path = process.env.REFERENCE_IMAGE_PATH;
  const bytes = await readFile(path);
  const ticket = await post('/api/v1/assets', {
    fileName: basename(path), contentType: 'image/png', fileSize: bytes.length,
  });
  const upload = await fetch(ticket.uploadUrl, {
    method: ticket.method,
    headers: { 'Content-Type': ticket.contentType },
    body: bytes,
    signal: AbortSignal.timeout(60_000),
  });
  if (!upload.ok) throw new Error('Asset upload failed: ' + upload.status);
  referenceUrl = (await post(ticket.completeUrl, {})).url;
}
if (referenceUrl) inputs.referenceImageUrls = [referenceUrl];
const spec = { model: 'seedance-2-mini', inputs };

const quote = await post('/api/v1/jobs/quote', spec);
console.log('Maximum USD reservation:', quote.maximum.amount);

const maxCostUsd = process.env.I2V_MAX_COST_USD;
const operationKey = process.env.I2V_IDEMPOTENCY_KEY;
if (maxCostUsd && operationKey) {
  const request = JSON.stringify({ ...spec, maxCostUsd, expectedRevision: quote.expectedRevision });
  const receiptPath = process.env.I2V_RECEIPT_PATH;
  if (!receiptPath) throw new Error('Set I2V_RECEIPT_PATH');
  await writeFile(receiptPath, JSON.stringify({ operationKey, request }), {
    flag: 'wx', mode: 0o600,
  });
  const task = await post('/api/v1/jobs/createTask', request, {
    'Idempotency-Key': operationKey,
  });
  console.log('Task ID:', task.taskId);
}
```

A quote creates no task or reservation. At submission the service checks the current model revision and USD ceiling. A quote can change before submission. If either check fails, get a new quote and confirm the revised request before creating a new logical submission.

## Recover or poll with Python

After a timeout, make a read-only receipt request using the **original API key and original Idempotency-Key**. The lookup never submits a task.

| Receipt status | Next action |
| --- | --- |
| `accepted` | Save the returned task ID and query `recordInfo`. |
| `pending` | Wait for `Retry-After` and check the same receipt. Keep the original key. |
| `retryable` | Wait for `Retry-After` and replay the original body with the original key. |
| `rejected` | Inspect the original response or correct the request. A corrected request is a new logical submission. |
| HTTP 404 | Check the credentials and key used for the original request. If replaying that same request, keep both the original body and key. |

```python
import json
import os
from urllib.parse import urlencode
from urllib.request import Request, urlopen

origin = "https://api.i2v.ai"
headers = {"Authorization": "Bearer " + os.environ["I2V_API_KEY"]}

def read(path, headers):
    with urlopen(Request(origin + path, headers=headers), timeout=20) as response:
        return json.load(response), response.headers.get("Retry-After")

receipt, retry_after = read("/api/v1/jobs/submission", {
    **headers, "Idempotency-Key": os.environ["I2V_IDEMPOTENCY_KEY"],
})
if receipt["status"] == "accepted":
    query = urlencode({"taskId": receipt["taskId"]})
    task, _ = read("/api/v1/jobs/recordInfo?" + query, headers)
    print(task["status"], task.get("lifecycle"), task["output"])
else:
    print(receipt["status"], "Retry-After:", retry_after)
```

API image and video tasks can include `lifecycle.phase`. The existing `status` field remains stable. A phase of `reconciling` means the original task still needs verification. Keep checking it after `pollAfterSeconds`. On success read `output[].url`. For production delivery, use [signed webhooks](/docs/webhooks) and poll as a fallback.

## Cancel a task before dispatch

Send `POST /api/v1/jobs/cancel` with `{"taskId":"YOUR_TASK_ID"}`. Cancellation is available for owned API image and video tasks that are still unclaimed by a worker. A successful cancellation releases the reservation and may be repeated safely. Queries and callbacks report `lifecycle.phase: cancelled` and keep the legacy terminal `status: fail` with error code `user_cancelled` in task queries. If the endpoint returns HTTP 409, continue querying the original task. Ending your SDK or HTTP wait does not cancel generation.