# BFXN API — Quickstart for developers and agents

BFXN gives you one API for video and music generation. You create a **task**, track it, and download the result. Every request is billed from your prepaid workspace balance at a price you can check for free beforehand.

- **Base URL:** `https://api.bfxn.com`
- **Auth:** `Authorization: Bearer <API_KEY>` (create keys in the [console](https://bfxn.com/console); one key per agent or app is recommended)
- **Format:** JSON over HTTPS. Every response has a `request_id`.
- **Money:** integer **micros** — 1 USD = 1,000,000 micros. `500000` means $0.50.
- **Machine-readable spec:** [`/openapi.json`](https://bfxn.com/openapi.json) (OpenAPI 3.1, stable `operationId`s, webhook schema included)

BFXN is invite-only. If you don't have access yet, request an invitation at [bfxn.com](https://bfxn.com).

## 1. Find a model and its parameters

```bash
curl https://api.bfxn.com/v1/models -H "Authorization: Bearer $BFXN_API_KEY"
curl https://api.bfxn.com/v1/models/kling-4.0/schema -H "Authorization: Bearer $BFXN_API_KEY"
```

`/v1/models` lists the models and modes enabled for your workspace. The schema endpoint returns a JSON Schema for each mode's `input` — required fields, allowed values, defaults and limits. Build requests from the schema rather than hard-coding parameters.

### Models at a glance

| Model | Mode | Key input fields | Billed per |
|---|---|---|---|
| `kling-4.0` | `text_to_video` | `prompt` (≤2500), `resolution` `720p`/`1080p`, `duration_seconds` 5/10/15, `aspect_ratio` `16:9`/`9:16`/`1:1`/`21:9` | second of video |
| `kling-4.0` | `image_to_video` | `image_asset_id` (first frame), optional `prompt` (≤2500), `resolution`, `duration_seconds` 5/10/15; aspect ratio follows the image | second of video |
| `muse-video` | `text_to_video` | `prompt` (≤4000), `resolution` `720p`/`1080p`, `duration_seconds` 5/10, `aspect_ratio` `16:9`/`9:16`/`1:1`, `generate_audio` | second of video |
| `muse-video` | `image_to_video` | `image_asset_id` (first frame), `prompt` (≤4000), `resolution`, `duration_seconds` 5/10, optional `aspect_ratio`, `generate_audio` | second of video |
| `suno-v6` | `text_to_music` | `prompt` (≤500, lyrics are written for you), `instrumental` | run (usually 2 tracks) |
| `suno-v6` | `custom` | `lyrics`, `style`, `title`, optional `exclude_styles`, `instrumental` | run (usually 2 tracks) |

Example inputs:

```json
{"model": "muse-video", "mode": "text_to_video", "input": {"prompt": "A paper lantern rising into a starry sky", "resolution": "720p", "duration_seconds": 5, "generate_audio": true}}
{"model": "suno-v6", "mode": "text_to_music", "input": {"prompt": "a warm acoustic guitar song about lanterns at night", "instrumental": false}}
{"model": "suno-v6", "mode": "custom", "input": {"lyrics": "[Verse]\nLanterns rise above the bay\n[Chorus]\nLight the way", "style": "indie folk, female vocals, gentle", "title": "Lanterns"}}
```

### Input images (image_to_video)

`image_to_video` animates your image as the first frame. Upload the image first and pass its `asset_id` as `input.image_asset_id`. Images must be PNG or JPEG, up to 10 MB, 300–3840 px per side with the shorter side at most 2160 px, aspect ratio between 0.4 and 2.5. Assets can be used for 30 days.

```bash
# 1. Ask for a one-time upload URL with the exact file size
curl https://api.bfxn.com/v1/assets/uploads \
  -H "Authorization: Bearer $BFXN_API_KEY" -H "Content-Type: application/json" \
  -d '{"filename": "frame.png", "content_type": "image/png", "bytes": 482113}'
# → {"asset": {"asset_id": "asset_...", "status": "pending_upload", ...}, "upload": {"method": "PUT", "url": "https://...", "headers": {...}, "expires_at": "..."}}

# 2. PUT the file to upload.url with exactly the returned headers (within 15 minutes)
curl -X PUT "<UPLOAD_URL>" -H "Content-Type: image/png" -H "x-cos-server-side-encryption: AES256" --data-binary @frame.png

# 3. Confirm; safe to retry. status becomes "ready", or "rejected" with reject_reason
curl -X POST https://api.bfxn.com/v1/assets/<ASSET_ID>/complete -H "Authorization: Bearer $BFXN_API_KEY"
```

If the image is already online, `POST /v1/assets/import` with `{"url": "https://..."}` downloads and verifies it in one call (`201`, status `ready`). Only public HTTPS addresses are fetched; on `503` retry later or upload the file instead. `GET /v1/assets/<ASSET_ID>` returns the status (`pending_upload`, `ready`, `rejected`, `expired`).

```json
{"model": "kling-4.0", "mode": "image_to_video", "input": {"image_asset_id": "asset_...", "prompt": "The camera slowly pushes in", "duration_seconds": 5}}
```

Quotes and tasks with an asset that is missing, not ready or expired return `422` (`asset_not_ready`, `asset_rejected`, or `invalid_parameter` with `param: "input.image_asset_id"`).

The schema is the source of truth: values outside it are rejected with `422 invalid_parameter` and a `param` pointing at the field.

## 2. Get a quote (free)

```bash
curl https://api.bfxn.com/v1/quotes \
  -H "Authorization: Bearer $BFXN_API_KEY" -H "Content-Type: application/json" \
  -d '{"model":"kling-4.0","mode":"text_to_video","input":{"prompt":"Clouds moving over a lighthouse at sunrise","duration_seconds":5}}'
```

The response shows the normalized `input` (with defaults applied), the billing `unit` and `quantity`, `amount_micros`, and a `quote_id` valid for 30 minutes. Quotes never touch your balance.

## 3. Create a task

```bash
curl https://api.bfxn.com/v1/tasks \
  -H "Authorization: Bearer $BFXN_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1234-video-1" \
  -d '{
    "model": "kling-4.0",
    "mode": "text_to_video",
    "input": {"prompt": "Clouds moving over a lighthouse at sunrise", "duration_seconds": 5},
    "quote_id": "<QUOTE_ID>",
    "max_amount_micros": 600000,
    "callback_url": "https://hooks.example.com/bfxn",
    "metadata": {"order": "1234"}
  }'
```

Returns `202` with `task_id` and `status_url`. Fields:

| Field | Required | Notes |
|---|---|---|
| `model`, `mode`, `input` | yes | `input` must match the mode's JSON Schema |
| `Idempotency-Key` header | yes | 1–255 visible ASCII characters, unique per logical request |
| `quote_id` | no | Locks the quoted price if still valid and the input matches |
| `max_amount_micros` | no | Budget cap; the task is rejected with `budget_exceeded` if it may cost more |
| `callback_url` | no | Public `https` URL (default port) for signed webhooks |
| `metadata` | no | Up to 16 string values, echoed in tasks and webhooks |

When the task is accepted, its maximum cost is **reserved** from your balance. On success you are charged the actual amount and any difference is released; on failure or cancellation the reservation is released in full.

**Idempotency.** If a create request times out, retry it with the **same** `Idempotency-Key` and body: you get the original task back (`202` with `Idempotent-Replayed: true`), never a duplicate charge. Reusing a key with a different body returns `409 idempotency_conflict` together with the original `task_id`. Keys are kept for 24 hours.

## 4. Track the task

Either poll, or wait for the webhook (section 6).

```bash
curl https://api.bfxn.com/v1/tasks/<TASK_ID> -H "Authorization: Bearer $BFXN_API_KEY"
```

Poll every 5–10 seconds until `status` is final.

| `status` | Meaning |
|---|---|
| `queued` | Accepted, waiting to be sent to the model |
| `running` | The model is generating |
| `finalizing` | Generation finished; preparing delivery |
| `succeeded` | Done — see `outputs` and `billing.charged_micros` |
| `failed` | See `error.code`; the reservation was released |
| `canceled` | Canceled before it was sent to the model; released |

`status_reason` may explain a wait: `waiting_for_capacity`, `awaiting_confirmation` (we are confirming the model provider accepted the job — it will not be submitted twice), or `retrying_delivery`. `billing.state` is `reserved`, `charged` or `released`.

Failed tasks carry `error.code`: `content_rejected`, `generation_failed`, `delivery_failed`, `asset_fetch_failed` or `timeout`. You are not charged for failed tasks.

Other task endpoints: `GET /v1/tasks` (newest first, filters `model`, `status`, `created_after`, `created_before`, `limit` up to 100, `cursor`), `POST /v1/tasks/<TASK_ID>/cancel` (only before the task is sent to the model; otherwise `409 task_not_cancelable`), and `GET /v1/balance` (available and reserved balance, active tasks and your concurrency limit).

## 5. Download the result

`outputs` is an array (video and audio share the same shape). A Suno run usually returns two tracks, so expect more than one item:

```json
[
  {"type": "audio", "mime_type": "audio/mp4", "url": "https://...", "expires_at": "2026-11-29T03:22:17.000Z", "bytes": 3797240, "duration_seconds": 206.96, "title": "Lanterns"},
  {"type": "audio", "mime_type": "audio/mp4", "url": "https://...", "expires_at": "2026-11-29T03:22:17.000Z", "bytes": 3675676, "duration_seconds": 198.84, "title": "Lanterns"}
]
```

`duration_seconds` and `title` are present when the model reports them. Download links are signed and valid for 15 minutes (`expires_at`); every `GET /v1/tasks/<TASK_ID>` returns fresh links, so fetch the task again when one expires. Task lists and webhooks do not include links.

**Retention.** Result files are kept for **30 days** after the task succeeds — the task's `files_expire_at` tells you exactly until when. Copy anything you need to your own storage before then. After that, `files_expired` is `true` and outputs have `url: null`, while the task, its input and billing remain available.

## 6. Webhooks

If you pass `callback_url`, we `POST` an event when the task reaches a final state: `task.succeeded`, `task.failed` or `task.canceled`.

```json
{
  "id": "evt_...",
  "type": "task.succeeded",
  "created_at": "2026-11-28T10:00:00.000Z",
  "data": {"task": {"task_id": "task_...", "status": "succeeded", "billing": {"state": "charged", "charged_micros": 500000}, "metadata": {"order": "1234"}}}
}
```

`data.task` has the same shape as `GET /v1/tasks/<TASK_ID>`, without download links.

**Signing secret.** A workspace owner creates it in Console → Webhooks (shown once, starts with `whsec_`). Events are not sent until a secret exists. When you rotate, the previous secret keeps signing for 24 hours, so a request may carry two signatures.

**Verify every request** ([Standard Webhooks](https://www.standardwebhooks.com/)):

1. Read the raw body and the `webhook-id`, `webhook-timestamp`, `webhook-signature` headers.
2. Compute `base64(HMAC-SHA256(key, "{webhook-id}.{webhook-timestamp}.{raw body}"))`, where `key` is the base64-decoded part of the secret after `whsec_`.
3. Accept if it equals any of the space-separated `v1,<signature>` values, and the timestamp is within 5 minutes of now.
4. Deduplicate by `webhook-id` (retries reuse it), respond `2xx` quickly, then do your work.

Node.js:

```js
import crypto from "node:crypto";

export function verifyBfxnWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"], ts = headers["webhook-timestamp"], sigs = headers["webhook-signature"] || "";
  if (!id || !ts || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const key = Buffer.from(secret.slice("whsec_".length), "base64");
  const expected = crypto.createHmac("sha256", key).update(id + "." + ts + "." + rawBody).digest();
  return sigs.split(" ").some((part) => {
    const [version, sig] = part.split(",");
    const got = Buffer.from(sig || "", "base64");
    return version === "v1" && got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}
```

Python:

```python
import base64, hashlib, hmac, time

def verify_bfxn_webhook(secret: str, headers: dict, raw_body: bytes) -> bool:
    msg_id, ts, sigs = headers.get("webhook-id"), headers.get("webhook-timestamp"), headers.get("webhook-signature", "")
    if not msg_id or not ts or abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()).decode()
    return any(p.startswith("v1,") and hmac.compare_digest(p[3:], expected) for p in sigs.split(" "))
```

**Delivery.** Each attempt waits up to 10 seconds. Non-`2xx` responses, timeouts and redirects (which are not followed) are retried after 5, 30 and 120 seconds — four attempts in total, same `webhook-id` and body, freshly signed each time. You can see delivery results and send a test event (`webhook.test`) in Console → Webhooks. The callback host must resolve to public addresses; private and internal addresses are refused.

## Errors

Errors use one shape: `{"request_id": "...", "error": {"code": "...", "message": "...", "param": "..."}}`.

Every call made with a valid key — including rejected ones — appears in the console under **Requests** for 30 days (method, path, status, error code, key, duration; never the request body). Filter by key, status or `request_id` to see what your integration actually sent, and quote the `request_id` when you contact support.

| HTTP | `error.code` | What to do |
|---|---|---|
| 401 | `invalid_api_key`, `api_key_revoked` | Check the key or create a new one |
| 402 | `insufficient_balance` | Top up, then create the task again |
| 403 | `ip_not_allowed` | The message shows the IP we saw; add it to the key's allowlist |
| 403 | `model_not_enabled`, `permission_denied` | Ask us to enable the model |
| 404 | `not_found` | Check the ID; resources from other workspaces are not visible |
| 409 | `idempotency_conflict` | Use a new `Idempotency-Key` for a different request |
| 409 | `quote_expired`, `quote_mismatch` | Get a new quote, or omit `quote_id` |
| 409 | `task_not_cancelable` | The task already went to the model; wait for the result |
| 422 | `invalid_parameter` | Fix the field named in `error.param` (e.g. `input.duration_seconds`) |
| 422 | `budget_exceeded` | Raise `max_amount_micros` or change the input |
| 429 | `concurrency_limit`, `model_queue_full` | Wait for `Retry-After`, retry with the same `Idempotency-Key` |
| 503 | `model_paused`, `service_unavailable` | Retry after `Retry-After` |

Rule of thumb for agents: **change the request** on 4xx validation errors, **retry with the same Idempotency-Key** on timeouts, 429 and 503, and **look up the task by ID** once you have a `task_id`.

## Security checklist

- Keep API keys and the webhook secret server-side (environment or secret manager), never in browsers, logs or URLs.
- Use one key per agent or app; restrict keys with an IP allowlist when your servers have fixed egress IPs.
- Revoke a key immediately in the console if it leaks; revocation takes effect on the next request.
- Verify webhook signatures and timestamps before trusting any event.
