> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# BeatAPI Quick Guide

> Create a BeatAPI key, submit your first image or video task, poll results, upload local media, add webhooks, and handle production retries safely.

BeatAPI uses one server-side API key across Text, Workflow, Realtime, Video, Image, and Effect APIs, plus [Social Data API](https://beatapi.io/data), [SEO Data API](https://beatapi.io/seo), and [Web Search API](https://beatapi.io/web-search-api). Check current rates on the [BeatAPI pricing page](https://beatapi.io/pricing) or connect your coding agent via [MCP integrations](https://beatapi.io/integrations). Start with the three steps below, then use the rest of this guide for synchronous text responses, shared task fields, uploads, limits, and production errors.

## First task in three steps

### 1. Create an API key

Create a key in [Dashboard → API Keys](https://beatapi.io/dashboard/apikeys), then load it into your shell without placing it in command history:

```bash
read -rsp "BeatAPI API key: " BEATAPI_API_KEY && echo
export BEATAPI_API_KEY
```

Send this header with every request. Image, video, effect, workflow and capability requests go to `https://api.beatapi.io`. Text requests go to `https://direct.beatapi.io` (see [Text API](/text-api#base-url-and-authentication)). The key is the same:

```http
Authorization: Bearer <BEATAPI_API_KEY>
```

### 2. Create a task

> **Note**
>
> A new account starts on free credit: a small starter balance (the amount depends on the sign-up region, and some regions start at zero) that can call only the models on the free-tier list. `nano-banana-2` is on it. Any model not on the list answers `403 forbidden` until the account's first top-up, and a top-up unlocks every model. `GET https://api.beatapi.io/v1/free-tier` returns the current list without a key. Each model also carries `requires_topup` in `GET /v1/media/models` and in Inspect and Search results: `true` means the model is refused until the first top-up, and `false` means at least one tier is open, not that every call will pass. In a region that starts at zero, the first call answers `402 insufficient_credits` until you top up. See [Free models](/free-models).

This minimal image request uses `POST /v1/images/tasks`:

```bash
curl https://api.beatapi.io/v1/images/tasks \
  -X POST \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana-2",
    "prompt": "Editorial product photograph on a warm stone pedestal."
  }'
```

A valid request returns `201 Created`. Save the returned `data.id`.

Enum values are case-insensitive, and older spellings (`1080P`, `4k`, `Fast`, `Quality`) are still accepted. The documentation writes only the canonical spelling.

### 3. Poll the result

```bash
curl https://api.beatapi.io/v1/tasks/task_8K2qA \
  -H "Authorization: Bearer $BEATAPI_API_KEY"
```

Replace `task_8K2qA` with the `data.id` from step 2. Wait `data.poll_after_seconds` seconds between polls. Use the value in the response rather than a constant of your own: it is present while the task runs, and today it is 5 for images, 8 for video and effects, and 10 for data and workflows. On `succeeded`, read `data.output.media` and stop polling. On `failed`, read `data.error_code`, `data.error_message` and `data.retryable`, then stop polling.

Polling `GET /v1/tasks/{task_id}` is not subject to the request-rate limit, so following `poll_after_seconds` never earns a `429` from BeatAPI. A `429`, `500` or `503` on a poll is transient and says nothing about the task: wait and ask again.

> **Note**
>
> Keep permanent API keys on trusted servers. Never place them in browser code, mobile code, scripts, logs, or screenshots. Realtime browsers receive only a short-lived `client_secret` created by your server.

## Submit, poll and download (Python)

A complete script that submits an image task, waits with a total timeout, handles `failed` and `retryable`, and downloads the result:

```python
import os
import time
import uuid
import requests

API = "https://api.beatapi.io"
HEADERS = {"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"}
TRANSIENT = {429, 500, 502, 503, 504}


def create_task(payload, idempotency_key, attempts=4):
    for attempt in range(attempts):
        # The same key on every attempt: only a 2xx answer is stored, so a retry cannot create a second task.
        response = requests.post(
            f"{API}/v1/images/tasks",
            headers={**HEADERS, "Idempotency-Key": idempotency_key},
            json=payload,
            timeout=60,
        )
        if response.ok:
            return response.json()["data"]
        try:
            error = response.json().get("error", {})
        except ValueError:  # a 502/504 from the network edge has no JSON body: retry it like a 503
            error = {"retryable": True}
        if not error.get("retryable") or attempt == attempts - 1:
            # Keep request_id: it identifies this call when you contact support.
            raise RuntimeError(f"{response.status_code} {error.get('code')}: {error.get('message')} ({error.get('request_id')})")
        time.sleep(error.get("retry_after_seconds") or min(2 ** attempt * 2, 60))  # a 429 says how long


def wait_for_task(task_id, total_timeout=1800):
    deadline = time.monotonic() + total_timeout
    wait = 5
    while time.monotonic() < deadline:
        response = requests.get(f"{API}/v1/tasks/{task_id}", headers=HEADERS, timeout=30)
        if response.status_code in TRANSIENT:  # not a verdict on the task
            time.sleep(float(response.headers.get("Retry-After", wait)))
            continue
        response.raise_for_status()
        task = response.json()["data"]
        if task["status"] in ("succeeded", "failed"):
            return task
        wait = task.get("poll_after_seconds", wait)  # the server's interval wins
        time.sleep(wait)
    # The task is still running on our side. Keep the ID and poll again later; do not resubmit.
    raise TimeoutError(f"{task_id} unfinished after {total_timeout}s")


def run(payload, attempts=3):
    for attempt in range(attempts):
        # A new key per attempt: the key of a failed task would replay that task's stored 201.
        task = create_task(payload, idempotency_key=str(uuid.uuid4()))
        task = wait_for_task(task["id"])
        if task["status"] == "succeeded":
            return task
        print(f"failed: {task['error_code']}: {task['error_message']} (request_id {task['request_id']})")
        if not task["retryable"]:  # content_policy_violation, bad_request: change the request
            break
    raise RuntimeError("task failed")


task = run({"model": "nano-banana-2", "prompt": "Editorial product photograph on a warm stone pedestal."})
for index, media in enumerate(task["output"]["media"]):
    file = requests.get(media["url"], timeout=120)  # no key needed; save it, the link expires
    file.raise_for_status()
    with open(f"result-{index}.{media['mime_type'].split('/')[-1]}", "wb") as handle:
        handle.write(file.content)
```

* **Total timeout.** The script gives up after 1800 seconds (30 minutes). The slowest models typically finish in about 400 seconds, so this leaves room for queueing without hanging forever. Giving up is your decision, not the task's: BeatAPI itself stops a task only after its [processing window](#how-long-things-are-kept).
* **A create error is retried only when it says so.** `create_task` retries when the error has `retryable: true`, waits `retry_after_seconds` on a `429`, and sends the same `Idempotency-Key` each time: only `2xx` answers are stored, so a retry cannot create a second task.
* **`failed` is a normal answer.** The HTTP status is `200`; the credits reserved for the task are refunded. Retry only when `retryable` is `true`.
* **One key per logical request.** Reusing the key of a failed task returns that stored task, not a new one.

## Get results by webhook

Instead of polling you can register an HTTPS endpoint with `POST /v1/webhooks`. BeatAPI then posts `task.succeeded` or `task.failed` to it when a task finishes, with the same task object that `GET /v1/tasks/{task_id}` returns. Verify the signature, deduplicate by event ID, and keep a slow reconciliation poll as the fallback. The payloads, headers, retries and verification code are on the [Webhooks](/webhooks) page.

To have one task's result delivered to one address instead, add `callback_url` to an image or video task request; it must be on the host of one of your webhook endpoints. See the One-off callback section of the [Webhooks](/webhooks) page.

## Choose an API

| API                       | Create operation                 | Input                                                      | Result                                       |
| ------------------------- | -------------------------------- | ---------------------------------------------------------- | -------------------------------------------- |
| Text (GPT-6.2)            | `POST /v1/responses`             | Text, images, tools, and reasoning controls                | Synchronous JSON or streamed text response   |
| Workflow — Music Video    | `POST /v1/music-video/tasks`     | Audio and tier-specific visual references                  | Complete Music Video and storyboard metadata |
| Workflow — Ecommerce      | `POST /v1/ecommerce-video/tasks` | Product images, duration, creative brief                   | Complete product video                       |
| Workflow — Video Analysis | `POST /v1/video-analysis/tasks`  | Uploaded video, analysis prompt, and depth                 | Analysis text and token usage                |
| Realtime                  | `POST /v1/realtime/sessions`     | Browser origin and fixed duration; then live `MediaStream` | Live generated WebRTC video                  |
| Video                     | `POST /v1/videos/tasks`          | Model-specific prompt and media references                 | One hosted video                             |
| Image                     | `POST /v1/images/tasks`          | Model-specific prompt and optional references              | One hosted image                             |
| Effect                    | `POST /v1/effects/tasks`         | Published Effect ID, images, supported options             | One hosted image or video effect result      |

Text calls go to `https://direct.beatapi.io` and return synchronously or as a server-sent event stream. Realtime creates a short-lived Session. Workflow, Video, Image, and Effect create operations return an asynchronous Task: store `data.id`, then poll the shared task endpoint. Polling `GET /v1/tasks/{task_id}` is not rate limited; wait `poll_after_seconds` between polls.

For GPT model selection, request formats, and streaming examples, see the [GPT guide](/text-api/gpt/responses).

## Get task status

`GET /v1/tasks/{task_id}`

| Parameter | Location | Type   | Required | Rules                                |
| --------- | -------- | ------ | -------- | ------------------------------------ |
| `task_id` | Path     | string | Yes      | Use `data.id` from a create response |

### Status values

| Status             | Meaning                                                  | Client action                                                    |
| ------------------ | -------------------------------------------------------- | ---------------------------------------------------------------- |
| `queued`           | Accepted and waiting                                     | Continue polling                                                 |
| `processing`       | Generation is running                                    | Continue polling                                                 |
| `storyboard_ready` | Music Video storyboard is available                      | Auto flow may continue; inspect if needed                        |
| `requires_action`  | Music Video manual review is waiting                     | Edit or compose shots                                            |
| `editing`          | Music Video shot edit is running                         | Continue polling                                                 |
| `composing`        | Music Video composition is running                       | Continue polling                                                 |
| `succeeded`        | Hosted output is ready                                   | Read `data.output` and stop polling                              |
| `failed`           | Task ended with an error; the answer is still HTTP `200` | Read `error` (`code`, `message`, `retryable`), then stop polling |

Image and video tasks only use `queued`, `processing`, `succeeded` and `failed`. The other statuses belong to Music Video.

### Status names in other APIs

If you are porting a client written for another API, map its statuses like this. BeatAPI has no `cancelled` status. A task still waiting for its model's capacity can be [cancelled](#cancel-a-queued-task): it then ends `failed` with `error_code` `task_cancelled` and is refunded. A task that has started runs to `succeeded` or `failed`, and a failed task is refunded.

| Other APIs often say                   | BeatAPI says                   | Notes                                                                 |
| -------------------------------------- | ------------------------------ | --------------------------------------------------------------------- |
| `pending`, `submitted`, `queued`       | `queued`                       | Accepted and waiting                                                  |
| `processing`, `running`, `in_progress` | `processing`                   | Keep polling                                                          |
| `completed`, `success`, `succeeded`    | `succeeded`                    | Read `data.output`                                                    |
| `failed`, `error`                      | `failed`                       | Read `error` (or the flat `error_code`, `error_message`, `retryable`) |
| `cancelled`, `canceled`                | `failed` with `task_cancelled` | Only a task still waiting in the queue can be cancelled               |

### Normalized Task fields

| Field                | Type            | Present                                           | Meaning                                                                                                                                                            |
| -------------------- | --------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`                 | string          | Always                                            | Stable task ID                                                                                                                                                     |
| `object`             | string          | Always                                            | `task`                                                                                                                                                             |
| `task_kind`          | string          | Always                                            | `workflow`, `effect`, `image`, `video`, or `data`                                                                                                                  |
| `capability_id`      | string          | Always                                            | Stable workflow, Effect, or generation model ID                                                                                                                    |
| `capability_version` | integer         | Always                                            | Always `1`                                                                                                                                                         |
| `workflow`           | string          | Workflow tasks                                    | `music-video` or `ecommerce-video`                                                                                                                                 |
| `effect_id`          | string          | Effect tasks                                      | Stable effect ID                                                                                                                                                   |
| `effect_version`     | integer         | Effect tasks                                      | Immutable selected effect version                                                                                                                                  |
| `media_type`         | string          | Image/video tasks                                 | `image` or `video`                                                                                                                                                 |
| `model`              | string          | Image/video tasks                                 | Stable model alias                                                                                                                                                 |
| `status`             | string          | Always                                            | Current lifecycle status                                                                                                                                           |
| `stage`              | string          | Always                                            | Repeats `status`; kept for compatibility                                                                                                                           |
| `storyboard`         | object          | Music Video                                       | Shot metadata when available                                                                                                                                       |
| `created_at`         | integer         | Always                                            | Unix timestamp                                                                                                                                                     |
| `updated_at`         | integer         | Always                                            | Unix timestamp                                                                                                                                                     |
| `completed_at`       | integer or null | Always                                            | Terminal Unix timestamp                                                                                                                                            |
| `poll_after_seconds` | integer         | While the task runs                               | Seconds to wait before the next poll: 5 for image, 8 for video and effect, 10 for data and workflows                                                               |
| `typical_seconds`    | object          | While the task runs, and only with enough history | `p50`, `p90`, `samples` and `window`: how long this model recently took. Past `p90` the task is running long.                                                      |
| `output`             | object or null  | Always                                            | `null` until success                                                                                                                                               |
| `usage`              | object          | Always                                            | Credits and billable duration                                                                                                                                      |
| `request_id`         | string          | Always                                            | Support/debug correlation ID of the create call; see [Errors](/errors#request-ids) for the format                                                                  |
| `error_code`         | string or null  | Always                                            | Machine-readable task failure                                                                                                                                      |
| `error_message`      | string or null  | Always                                            | Human-readable task failure                                                                                                                                        |
| `retryable`          | boolean         | Failed tasks only                                 | Whether submitting the task again could succeed                                                                                                                    |
| `error`              | object          | Failed tasks only                                 | `code`, `message` and `retryable` in one object, the same values as the three flat fields above, which stay                                                        |
| `queue`              | object          | While the task waits for its model's capacity     | `position` (1 is next), `ahead`, `queued_at` and `deadline` (Unix seconds). A task still waiting at `deadline` fails with `processing_unavailable` and is refunded |

### Usage and output fields

> **Note**
>
> Public response names such as `credits_reserved` are retained for API compatibility. All credit and balance values are decimal USD ledger amounts: 1 Credit = $1 USD. The Dashboard displays the same values with a `$\` symbol.

| Field                             | Type              | Meaning                                                                                                                                                                                                                       |
| --------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `usage.credits_reserved`          | number            | USD amount reserved for the operation                                                                                                                                                                                         |
| `usage.credits_charged`           | number            | USD amount charged; `0` on a failed task                                                                                                                                                                                      |
| `usage.billable_duration_seconds` | integer, optional | Duration used for USD calculation                                                                                                                                                                                             |
| `usage.credits_settled`           | number            | USD amount finalized after successful work; `0` on a failed task                                                                                                                                                              |
| `usage.credits_refunded`          | number            | USD amount returned after a failed task                                                                                                                                                                                       |
| `output.media`                    | object\[]         | Hosted result files                                                                                                                                                                                                           |
| `output.media[].type`             | string            | `image` or `video`                                                                                                                                                                                                            |
| `output.media[].url`              | string            | Result URL. Download and store any result you need to keep.                                                                                                                                                                   |
| `output.media[].mime_type`        | string            | Result MIME type                                                                                                                                                                                                              |
| `output.url`                      | string            | The primary result: the first video, or the first image when there is no video                                                                                                                                                |
| `output.r2_url`                   | string            | The same value as `output.url`, kept for older clients. Read `output.url`.                                                                                                                                                    |
| `output` of a data task           | object            | A data capability run as a task (such as `web.research`) has no `media`: `output` is the capability's own result object, the one its synchronous call returns, for example `object`, `status`, `research_notes` and `sources` |

### How long things are kept

| What                                              | How long                                                                                                                                                              |
| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Result files (`output.media[].url`)               | At least 72 hours after the task finishes. Download and store what you need to keep within that time; the link stops working afterwards.                              |
| Files you upload with `POST /v1/files`            | At least 72 hours after the upload. Upload again if you need the file later.                                                                                          |
| A task record (`GET /v1/tasks/{task_id}`)         | Kept separately from the files, so it can still answer after the files are gone, with links that no longer open. Store the ID, status and `usage` in your own system. |
| Stored capability results (`operation: "result"`) | 1 hour                                                                                                                                                                |
| An unfinished task (processing window)            | At most 24 hours. After that the task fails with `processing_timeout` and its reservation is refunded; some models use a shorter window.                              |
| Idempotency keys                                  | 24 hours                                                                                                                                                              |

On a failed task, `usage.credits_reserved` is the amount held at create, `usage.credits_charged` and `usage.credits_settled` are `0`, and `usage.credits_refunded` is the amount returned. An accepted task fails with one of seven codes: `content_policy_violation`, `bad_request` and `task_cancelled` (not retryable), and `processing_unavailable`, `processing_timeout`, `processing_failed` and `result_transfer_failed` (retryable). See [Errors](/errors#where-a-failure-shows-up).

## Cancel a queued task

`POST /v1/tasks/{task_id}/cancel`

A model can have a limit on how many tasks run at once. A create request for a model at its limit is still accepted: the task is charged, answers `queued`, and carries a `queue` object until it starts. A request that cannot wait (one that uploads its files in the same multipart call) is refused instead with `429 rate_limit_exceeded` and a `Retry-After` header, before anything is charged.

While a task waits in the queue, cancel it with this endpoint. The answer is the task, as `GET /v1/tasks/{task_id}` returns it: `status: "failed"`, `error_code: "task_cancelled"`, and the reservation refunded.

| Answer                | When                                                                              |
| --------------------- | --------------------------------------------------------------------------------- |
| `200`                 | The task was waiting and is now cancelled and refunded                            |
| `409 task_not_queued` | The task has already started or finished; it cannot be cancelled                  |
| `404 not_found`       | No such task for this account                                                     |
| `500 internal_error`  | The task was cancelled, but its refund has not completed yet; it will be refunded |

## List tasks

`GET /v1/tasks`

Lists your account's tasks, newest first. Each item is the task object `GET /v1/tasks/{task_id}` returns, so one parser reads both.

```bash
curl "https://api.beatapi.io/v1/tasks?status=failed&limit=20" \
  -H "Authorization: Bearer $BEATAPI_API_KEY"
```

| Parameter        | Type    | Rules                                                                                                                                           |
| ---------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`         | string  | `queued`, `processing`, `succeeded` or `failed`. Repeat the parameter or separate values with commas to take several.                           |
| `model`          | string  | The model ID you sent, matched exactly. An ID this gateway does not serve is `400 bad_request`                                                  |
| `created_after`  | string  | Unix seconds or an RFC 3339 time; tasks created at that moment or later                                                                         |
| `created_before` | string  | Unix seconds or an RFC 3339 time; tasks created before that moment, so adjacent ranges neither overlap nor leave a gap                          |
| `limit`          | integer | 1 to 100, default 20                                                                                                                            |
| `cursor`         | string  | The `next_cursor` of the previous page                                                                                                          |
| `api_key_id`     | integer | The numeric `id` of one of your API keys, from `GET /v1/account/keys`; only tasks submitted with that key. Any other value is `400 bad_request` |

An unknown parameter is `400 bad_request`. The answer is `{"data": {"object": "list", "data": [task, …], "has_more": true, "next_cursor": "…"}}`; the last page has no `next_cursor`.

* **The cursor is opaque.** Pass `next_cursor` back as `cursor` and do not build or edit one. It works only for the account that read that page; any other value is `400 bad_request`.
* **Status filters follow the lifecycle.** `status` filters by `queued`, `processing`, `succeeded` and `failed`. `processing` also matches a Music Video task that is at a stage such as `storyboard_ready`.
* **Synchronous calls are listed only when sent with an `Idempotency-Key`.** Social data, web, SEO and ads calls answer in the response. Without a key the result is not kept, so the call never appears here and `GET /v1/tasks/{task_id}` answers `404` for it; with a key it appears here and `GET /v1/tasks/{task_id}` returns its result.
* **A filtered page can be short, even empty.** With `model` or `api_key_id`, one page reads at most the 2,000 most recent tasks after the cursor and returns the matches among them, so it can hold fewer than `limit` items or none while `has_more` is `true`. Keep following `next_cursor` until `has_more` is `false`; a short or empty page is not the end of the list.
* **Rate limit.** `GET /v1/tasks` allows 60 requests per minute for the account, however many API keys it has; past that it answers `429 rate_limit_exceeded` with `Retry-After`. To follow one task, poll `GET /v1/tasks/{task_id}`, which has no such limit.

## Upload an input file

`POST /v1/files`

Use file upload when an input is local instead of already available at a public HTTPS URL.
Every upload must include an exact `Content-Length`; normal `curl`, browser, and SDK uploads set it automatically. Chunked uploads without a declared length are rejected before the body is buffered.

### Multipart fields

| Field     | Type   | Required | Default | Rules                                                                                                             |
| --------- | ------ | -------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| `file`    | binary | Yes      | —       | One supported file; video up to 100 MB, other types up to 50 MB. A multipart part over 100 MB is refused outright |
| `purpose` | string | No       | `input` | Ignored; the response always says `input`                                                                         |

```bash
curl https://api.beatapi.io/v1/files \
  -X POST \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -F "file=@./song.mp3" \
  -F "purpose=input"
```

You may also send the raw file body with its asset `Content-Type`.

| Asset    | Accepted extensions | Accepted MIME types                                                                           | Additional rule |
| -------- | ------------------- | --------------------------------------------------------------------------------------------- | --------------- |
| Image    | PNG, JPG/JPEG, WebP | `image/png`, `image/jpeg`, `image/webp`                                                       | Maximum 50 MB   |
| Audio    | MP3, WAV, AAC, M4A  | `audio/mpeg`, `audio/wav`, `audio/aac`, `audio/mp4`                                           | Maximum 50 MB   |
| Subtitle | SRT                 | `application/x-subrip`; `text/plain` only in a multipart upload whose filename ends in `.srt` | Maximum 50 MB   |
| Video    | MP4, MOV            | `video/mp4`, `video/quicktime`                                                                | Maximum 100 MB  |

Some common aliases are accepted and stored under the canonical type, for example `image/jpg` as `image/jpeg`, `audio/mp3` as `audio/mpeg`, and `text/plain` (with a `.srt` filename) as `application/x-subrip`. PDF, generic text, octet-stream, unsupported video containers, and ZIP uploads are refused with `400 bad_request`. The gateway trusts the declared `Content-Type`; when the filename has an extension, it must agree with that type. It does not inspect the file contents and does not read duration or dimensions. A file accepted by the upload can still be refused by the model or workflow that uses it, for example for duration or size rules, when you create the task. Workflow input URLs cannot be localhost, private-network, or data URLs.

Upload refusals are `400 bad_request` with one of these messages:

| Message                                                                                                     | Cause                                                    |
| ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `Content-Length is required for file uploads.`                                                              | No declared length.                                      |
| `Content-Length must be a positive integer.`                                                                | Invalid declared length.                                 |
| `File exceeds the declared upload limit.`                                                                   | Declared length is over the upload limit.                |
| `No file provided. Use multipart "file" field or a raw body.`                                               | No file in the request.                                  |
| `The uploaded file is empty.`                                                                               | Zero bytes.                                              |
| `Unsupported file type. Supported uploads are png, jpg, jpeg, webp, mp3, wav, aac, m4a, mp4, mov, and srt.` | Type or extension not accepted.                          |
| `File exceeds the 50 MB limit.`                                                                             | Over 50 MB (`File exceeds the 100 MB limit.` for video). |
| `File exceeds the 100 MB upload limit.`                                                                     | A multipart part over 100 MB.                            |
| `Could not read the uploaded file.`                                                                         | The file body could not be read.                         |
| `Could not read the multipart upload.`                                                                      | The multipart form could not be parsed.                  |

If the file cannot be stored, the upload answers `503` with `processing_unavailable` ("File storage is temporarily unavailable. Retry later; nothing was stored.") or `result_transfer_failed` ("The file could not be stored on our side. Retry; nothing was stored."). Retry with backoff.

### File response

```json
{
  "data": {
    "id": "file_6f1c2b9e-4d0a-4c58-9a57-2f0a8f3d7b11",
    "object": "file",
    "url": "https://files.beatapi.io/u/6f1c2b9e4d0a4c589a572f0a8f3d7b11.mp3",
    "key": "u/6f1c2b9e4d0a4c589a572f0a8f3d7b11.mp3",
    "mime_type": "audio/mpeg",
    "size_bytes": 1048576,
    "purpose": "input",
    "created_at": 1782210000
  }
}
```

| Field        | Type    | Present | Meaning                                                                                                           |
| ------------ | ------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| `id`         | string  | Always  | File ID, `file_<uuid>`                                                                                            |
| `object`     | string  | Always  | `file`                                                                                                            |
| `url`        | string  | Always  | HTTPS input URL                                                                                                   |
| `key`        | string  | Always  | Storage key, `u/<random>.<ext>`                                                                                   |
| `mime_type`  | string  | Always  | The canonical MIME type the file is stored and served under (for example `image/jpg` is reported as `image/jpeg`) |
| `size_bytes` | integer | Always  | Uploaded byte size                                                                                                |
| `purpose`    | string  | Always  | `input`                                                                                                           |
| `created_at` | integer | Always  | Unix timestamp                                                                                                    |

Use `data.url` in the model or workflow request. The model or workflow checks its own limits when you create the task; for example, Standard Music Video accepts 10–180 seconds of audio and Premium accepts 10–300.

## Check usage and limits

`GET /v1/usage`

Send an API key or your account's [personal access token](/personal-access-token); both return the same account-wide summary.

The one optional query parameter, `period`, sets the window the counts and breakdowns cover, ending now: `24h`, `7d`, `30d` or `all` (the default, the whole account history). `credit_balance` and `concurrency` are always current. Any other parameter, or another `period` value, is refused with `400`.

```bash
curl "https://api.beatapi.io/v1/usage?period=7d" \
  -H "Authorization: Bearer $BEATAPI_API_KEY"
```

| Field                | Type              | Meaning                                                                                             |
| -------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |
| `object`             | string            | `usage`                                                                                             |
| `period`             | string            | `24h`, `7d`, `30d` or `all`                                                                         |
| `since`, `until`     | integer, optional | Window bounds in unix seconds; absent for `all`                                                     |
| `account_name`       | string, optional  | Account display name                                                                                |
| `credit_balance`     | number            | Current USD balance; it may be negative                                                             |
| `total_tasks`        | integer           | Account task count                                                                                  |
| `credits_settled`    | number            | Settled USD amount                                                                                  |
| `credits_refunded`   | number            | Refunded USD amount                                                                                 |
| `concurrency`        | object            | Processing-task capacity summary                                                                    |
| `concurrency.limit`  | integer           | Account cap on tasks in flight. `0` means no cap: BeatAPI limits request rate, not concurrent tasks |
| `concurrency.active` | integer           | Tasks currently consuming processing capacity                                                       |
| `realtime`           | object, optional  | Realtime Session usage summary                                                                      |
| `realtime.sessions`  | integer           | Total Realtime Sessions                                                                             |
| `realtime.credits`   | number            | Realtime settled USD amount                                                                         |
| `realtime.active`    | integer           | Sessions in `ready`, `connecting`, or `active`                                                      |
| `by_workflow[]`      | object\[]         | Workflow compatibility breakdown                                                                    |
| `by_capability[]`    | object\[]         | All task kinds by stable capability                                                                 |
| `by_model[]`         | object\[]         | Image/video tasks by model alias                                                                    |
| `by_api_key[]`       | object\[]         | Task/credit totals by API key                                                                       |

Breakdown item fields:

| Array           | Required item fields                                            |
| --------------- | --------------------------------------------------------------- |
| `by_workflow`   | `workflow`, `tasks`, `credits_settled`                          |
| `by_capability` | `task_kind`, `capability_id`, `tasks`, `credits_settled`        |
| `by_model`      | `media_type`, `model`, `tasks`, `credits_settled`               |
| `by_api_key`    | `api_key_id`, `title`, `key_prefix`, `tasks`, `credits_settled` |

Music Video tasks paused at `storyboard_ready` or `requires_action` can have settled credits without counting as active processing work.

To see what each task or text request cost, read the per-request usage records with your account's [personal access token](/personal-access-token).

## Errors and retry policy

```json
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded: at most 10 successful requests per 1 minute(s). Retry after 60 seconds.",
    "retryable": true,
    "request_id": "202611260307541272151438268d9d6mNDNwzi9",
    "retry_after_seconds": 60
  }
}
```

Every error carries `code`, an English `message` that states the cause, and `request_id` (also sent in the `X-BeatAPI-Request-Id` response header; quote it when you [contact support](/errors#contact-support)); only a `429 rate_limit_exceeded` also carries `retry_after_seconds` and the `Retry-After` header; a `503` has no known wait, so retry it with backoff. `retryable` is present for every code in the table below. Branch on it: `false` means the same call will fail again until you change it.

### Public error codes

BeatAPI exposes only the stable public codes below. BeatAPI never names the supplier behind a model and does not pass on raw upstream bodies. [Errors](/errors) lists which code each failure produces at create and on an accepted task, and how the text endpoints fail before the model is called (this envelope) and during the call (the SDK's native error shape, with BeatAPI codes for our own refusals and rewritten codes for failures on the model's side). These values appear in response `error.code`. Terminal asynchronous failures may also return the applicable value in task `error_code`.

| Code                            | Meaning                                                                                                                                                                                                                                      | Client action                                                                                         |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `bad_request`                   | Malformed JSON, or request fields, combinations, formats, URLs, or limits are invalid — at create, or on an accepted task whose parameter or input the model refused. The message names the field                                            | Correct the request before retrying                                                                   |
| `missing_api_key`               | No API key was sent                                                                                                                                                                                                                          | Send `Authorization: Bearer <key>`                                                                    |
| `invalid_api_key`               | The key is wrong, expired, disabled, or has used up its own quota; the message says which                                                                                                                                                    | Check the active key in the dashboard                                                                 |
| `unauthorized`                  | Legacy name for a `401`, replaced by `missing_api_key` and `invalid_api_key` on 2026-09-29; it may still appear                                                                                                                              | Treat it like `invalid_api_key`                                                                       |
| `forbidden`                     | The key or account cannot perform the operation, for example a model not on the [free-tier list](/free-models), the key's IP allowlist, or the key's group                                                                                   | Read the message; a top-up unlocks every model for free-credit accounts                               |
| `not_found`                     | An unknown model on the text endpoints, an unknown capability, or a task or resource that does not exist or is not owned by this API key's account. An uncatalogued model on the image and video task endpoints is `400 bad_request` instead | Check the ID and API-key ownership                                                                    |
| `method_not_allowed`            | The path exists but not under this method; the `Allow` header lists the methods it accepts                                                                                                                                                   | Use a method from `Allow`                                                                             |
| `insufficient_credits`          | Insufficient balance: the account balance is zero or below the price of this request, or the key still has quota but less than the price                                                                                                     | Top up (or raise the key's quota) before sending another paid request                                 |
| `idempotency_conflict`          | The idempotency key was already used with a different request body                                                                                                                                                                           | Reuse the key only for the same logical request, or use a new key                                     |
| `rate_limit_exceeded`           | The API key exceeded a request-rate limit, including the free-model limits; or, at create, the model is at its concurrency limit and the request cannot wait in its queue                                                                    | Honor `Retry-After` or `retry_after_seconds`                                                          |
| `content_policy_violation`      | The prompt, input media, or result was refused by content moderation                                                                                                                                                                         | Revise the prompt or media before submitting a new request                                            |
| `processing_unavailable`        | The model is temporarily unavailable or at capacity (not your rate limit)                                                                                                                                                                    | Retry later with backoff; continue polling an already accepted task                                   |
| `processing_failed`             | Processing failed for a reason on our side                                                                                                                                                                                                   | Stop polling, inspect `error_message` and refund fields, then retry with backoff                      |
| `processing_timeout`            | Processing did not finish within the processing window (at most 24 hours)                                                                                                                                                                    | Stop polling, inspect refund fields, and submit a new request if needed                               |
| `result_transfer_failed`        | BeatAPI could not persist the generated result to first-party storage                                                                                                                                                                        | Stop polling, inspect refund fields, and retry the operation if needed                                |
| `result_expired`                | `POST /v1/capabilities/run` with `operation: "result"` found no stored result; results are kept for one hour (`404`)                                                                                                                         | Run the capability again                                                                              |
| `not_implemented`               | The endpoint is published but this gateway does not serve it yet (`501`)                                                                                                                                                                     | Do not retry                                                                                          |
| `realtime_disabled`             | Realtime Video is not enabled on this deployment                                                                                                                                                                                             | Realtime Video is not enabled on this deployment; there is no self-service action, so contact support |
| `realtime_capacity_unavailable` | Realtime capacity is temporarily unavailable                                                                                                                                                                                                 | Retry shortly with backoff; no delay is indicated                                                     |
| `realtime_session_expired`      | The Realtime Session can no longer be used                                                                                                                                                                                                   | Create a new Session and client secret                                                                |
| `origin_not_allowed`            | The browser origin is not allowed for the Realtime Session                                                                                                                                                                                   | Use an exact configured HTTPS origin                                                                  |
| `invalid_client_secret`         | The Realtime client secret is invalid or no longer usable                                                                                                                                                                                    | Create a new Session and use its new client secret                                                    |
| `transport_not_allowed`         | The requested Realtime transport is not allowed                                                                                                                                                                                              | Use a transport documented by the Realtime API                                                        |
| `task_not_queued`               | `POST /v1/tasks/{task_id}/cancel` on a task that has already started or finished (`409`)                                                                                                                                                     | Keep polling the task; it cannot be cancelled                                                         |
| `task_cancelled`                | Task `error_code` only: you cancelled the task while it waited in the queue, and it was refunded                                                                                                                                             | Submit a new task if you still want the result                                                        |
| `internal_error`                | BeatAPI encountered an unexpected internal error                                                                                                                                                                                             | Retain `request_id`; retry only when safe or [contact support](/errors#contact-support)               |

| HTTP  | Code                                                                                          | `retryable` | Client action                                                                      |
| ----- | --------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------- |
| `400` | `bad_request`, `content_policy_violation`                                                     | `false`     | Correct fields, combinations, formats, URLs, limits, or the input                  |
| `401` | `missing_api_key`, `invalid_api_key`                                                          | `false`     | Send or replace the Bearer key                                                     |
| `402` | `insufficient_credits`                                                                        | `false`     | Top up before a new paid request                                                   |
| `403` | `forbidden` or Realtime origin error                                                          | `false`     | Check permission or exact browser origin                                           |
| `404` | `not_found`, `result_expired`                                                                 | `false`     | Check the model, reference, or ID and API-key ownership                            |
| `405` | `method_not_allowed`                                                                          | `false`     | Use a method from the `Allow` header                                               |
| `409` | `idempotency_conflict`                                                                        | `false`     | Reuse a key only with the same logical request body                                |
| `429` | `rate_limit_exceeded`                                                                         | `true`      | Honor `Retry-After` or `retry_after_seconds`                                       |
| `500` | `internal_error`                                                                              | `true`      | Preserve `request_id`; retry once, then [contact support](/errors#contact-support) |
| `501` | `not_implemented`                                                                             | `false`     | Do not retry                                                                       |
| `503` | `processing_unavailable`, `processing_timeout`, `processing_failed`, `result_transfer_failed` | `true`      | Retry with backoff                                                                 |

BeatAPI does not answer `502` or `504`; one you still see came from the network edge, has no JSON body, and is retried like a `503`.

Idempotency:

* Send the key in the `Idempotency-Key` request header. Workflow, Image, Video, and Effect task creation accept an optional key, and so does `POST /v1/capabilities/run`. Realtime Session create requires it (up to 255 characters).
* A key is remembered for 24 hours. A key longer than 255 characters is `400 bad_request`.
* The same key with a different body or path is `409 idempotency_conflict`. So is the same key while the first request is still running.
* Repeating the identical request returns the stored response with the header `Idempotent-Replayed: true`.
* Only `2xx` responses are stored, so after a `400` or `402` you can retry with the same key.

## Production checklist

* Use the exact origin: `https://api.beatapi.io` for image, video, effect, workflow and capability calls, `https://direct.beatapi.io` for text calls.
* Keep permanent API keys on trusted servers.
* Validate required/optional fields, enums, limits, and conditional rules from the selected API page.
* Store task/Session IDs and `request_id` before starting background work.
* Poll every `poll_after_seconds` and stop at the documented terminal or action state.
* Download and store the results you need to keep within 72 hours of completion.
* Honor status codes, `Retry-After`, and `retry_after_seconds`.
* Verify webhook signatures against raw bytes before JSON parsing. Webhooks send only `task.succeeded` and `task.failed`, with 3 attempts (retries after 1 minute and 5 minutes). A task that times out sends `task.failed` too, but keep a slow poll as the source of truth.
* Record credit reservations, settlements, refunds, errors, and final output URLs.
* Review the [Privacy Policy](https://beatapi.io/privacy-policy) and [Terms of Service](https://beatapi.io/terms-of-service) before processing cameras, faces, voices, or reference assets.