Skip to navigation

Development Guide

View as Markdown

The Quick Guide gets one request working. This page covers what changes when the code has to keep working in production.

Two shapes of call

BeatAPI has exactly two request lifecycles, and almost every integration mistake comes from treating one as the other.

TextWorkflow, Image, Video, Effect
ReturnsThe answer, immediatelyA task ID, immediately
LatencySecondsSeconds to minutes
StreamingServer-sent eventsNot applicable
CompletionThe HTTP responsePoll, or receive a webhook
BilledOn the responseOn settlement, refundable on failure

Text is synchronous: POST /v1/chat/completions, /v1/responses, /v1/messages, or the Gemini-compatible endpoint returns the result. Everything else accepts the work and hands back an ID.

The asynchronous lifecycle

  1. Submit — POST /v1/images/tasks (or videos, effects, video-analysis, music-video, ecommerce-video). A 201 means accepted, not finished.
  2. Store the ID — persist data.id and data.request_id before starting any background work. A crash between the response and the write leaves a task you have paid for and cannot find.
  3. Wait — poll GET /v1/tasks/{task_id}, or register a webhook.
  4. Read the result — on succeeded, use data.output.media. On failed, read data.error_code and the refund fields.

Polling

import time
import random
import requests
TERMINAL = {"succeeded", "failed"}
def wait_for_task(api_key, task_id, timeout=1800):
url = f"https://api.beatapi.io/v1/tasks/{task_id}"
headers = {"Authorization": f"Bearer {api_key}"}
deadline = time.time() + timeout
wait = 5.0
while time.time() < deadline:
response = requests.get(url, headers=headers, timeout=30)
if response.status_code in (429, 500, 502, 503, 504): # 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 TERMINAL:
return task
# The server states the interval; jitter keeps a fleet of workers from polling in lockstep.
wait = task.get("poll_after_seconds", wait)
time.sleep(wait + random.uniform(0, wait * 0.2))
raise TimeoutError(f"task {task_id} did not finish within {timeout}s")

Three properties of that loop matter:

  • It stops on terminal states, not on a guess about elapsed time. A finished task never changes again.
  • It waits poll_after_seconds. The response states the interval for the task’s kind (today 5, 8 or 10 seconds), so read it instead of choosing your own; a little jitter avoids synchronising polls across concurrent tasks. Polling more often does not make a task finish sooner.
  • It treats a transient error as “wait”, not “fail”. BeatAPI does not apply the request-rate limit to GET /v1/tasks/{task_id}, so following poll_after_seconds never earns a 429; the loop still retries a 429, 500 or 503 because none of them says anything about the task. Honour Retry-After.
  • It has a total timeout of 1800 seconds. The slowest models typically finish in about 400 seconds, so 30 minutes leaves room for queueing. The Quick Guide script uses the same value. When your timeout passes, keep the task ID and poll again later instead of resubmitting: BeatAPI stops a task itself only after its processing window, at most 24 hours.

Music Video tasks have non-terminal states that need a decision rather than more polling — storyboard_ready and requires_action. Treating them as “still working” polls forever. The Quick Guide lists every status and the action each one calls for.

Webhooks instead of polling

Register an endpoint with POST /v1/webhooks and BeatAPI posts the terminal state to it. This removes the polling loop entirely, at the cost of needing a reachable HTTPS endpoint.

Verify the signature against the raw request bytes before parsing JSON — re-serialising the body changes it and the signature will not match. The event carries the same task object as GET /v1/tasks/{task_id}; deduplicate by event id. See Webhooks.

Keep a slow reconciliation poll even with webhooks configured. A delivery can fail; a task that has been in processing for far longer than its model’s normal runtime is worth checking directly.

Errors

Every failure carries a stable error.code, an English message that states the cause, retryable, and a request_id. Log the request_id (also the X-BeatAPI-Request-Id response header) — it identifies the exact call when you contact support.

{
"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
}
}
HTTPRetry?What it means
400NoThe request is wrong. Retrying sends the same wrong request
401Nomissing_api_key or invalid_api_key: the key is missing, wrong, expired, disabled, or has used up its own quota
402Noinsufficient_credits: the balance is zero or below the price, or the key’s remaining quota is below the price. Top up
403Noforbidden: the key or account cannot perform this operation
404Nonot_found: unknown text model, or a wrong ID or one that belongs to another account (an uncatalogued image or video model is 400)
405Nomethod_not_allowed: the path exists but not under this method; the Allow header lists the methods it accepts
409Noidempotency_conflict: an idempotency key was reused with a different body
410Norealtime_session_expired: the Realtime Session can no longer be used. Create a new one
413Noread_request_body_failed: the body is too large (text endpoints only; the image and video endpoints answer 400). Send a smaller one
429Yes, after Retry-AfterRequest-rate limit, or a text model at capacity
500, 503Yes, with backoffTransient. Poll known tasks rather than resubmitting
501Nonot_implemented: the endpoint is published but this gateway does not serve it yet

retryable in the error says the same thing per code, so you can branch on it instead of the status. BeatAPI does not answer 502 or 504; one that reaches you came from the network edge and is retried like a 503. Every code is listed in Errors.

import requests
response = requests.post(
"https://api.beatapi.io/v1/images/tasks",
headers={"Authorization": f"Bearer {api_key}"},
json={"model": "nano-banana-2", "prompt": "a cute panda"},
timeout=30,
)
if not response.ok:
error = response.json().get("error", {})
# request_id is the only thing that identifies this call later.
log.error("beatapi failed", code=error.get("code"), request_id=error.get("request_id"))
if response.status_code == 402:
alert_billing()
elif response.status_code == 429:
schedule_retry(after=error.get("retry_after_seconds", 10))

A 500 on a submit is ambiguous: the task may or may not have been created. Resubmitting blindly can pay for the same work twice. Send an Idempotency-Key on task creation and reuse it on the retry — BeatAPI returns the original task instead of creating a second one.

Rate limits

BeatAPI limits how often an account calls. It does not cap how many tasks run at once, and the two cases fail differently.

  • Request rate — successful requests per minute for the account, answered with 429 rate_limit_exceeded, Retry-After and retry_after_seconds. The allowance rises with lifetime top-ups, and a stricter limit can be attached to an individual key. Your current allowance and the next tier are on the Billing page of the dashboard; there is no public API that returns them. Free models have their own, separate limit; see Free models.
  • Concurrency — there is no per-account cap on tasks in flight. GET /v1/usage reports concurrency.active (tasks being processed now) and a concurrency.limit of 0, which means no cap. When a model itself is at capacity you do not get a rate-limit error on a task create: it answers 503 processing_unavailable, which you retry with backoff. A text call to a model at capacity can answer 429 rate_limit_exceeded (“This model is receiving too many requests”).

GET /v1/tasks/{task_id} is not subject to the request-rate limit. The list GET /v1/tasks has a limit of its own: 60 requests per minute for the account, however many API keys it has, answered with 429 rate_limit_exceeded, Retry-After and retry_after_seconds. See List tasks.

Retries that do not cost money

  • Retry 429 and 5xx (every 5xx from BeatAPI is a 500 or a 503) with backoff. Do not retry 400, 401, 402, 403, 404, or 409 — they carry retryable: false.
  • Use exponential backoff with jitter, and a ceiling.
  • Put an Idempotency-Key on every task creation so a retried submit cannot double-charge.
  • After a failed submit, poll before resubmitting if you have an ID.
  • Cap total attempts. A permanently failing request retried forever is an outage that bills.

Cost control

  • Set an output cap on text calls. Output is the expensive half; max_tokens is the simplest lever there is.
  • Match the model to the step. Classification and routing do not need the top tier.
  • Watch the tiered models. Most GPT-6 models bill a higher rate above 272K input tokens and Grok above 200,000 tokens (each model’s page says which); the two DeepSeek HC (high-cache) models, on weekdays 09:00–12:00 and 14:00–18:00 Beijing time, and Hunyuan hy3 bill a higher rate during published peak windows, while the regular paid DeepSeek models bill one rate at all hours. A long-running agent or a scheduled batch can cross either line invisibly. Each response’s usage record shows which rate was applied.
  • One key per component. by_api_key in GET /v1/usage then attributes spend without any work on your side.
  • Reconcile refunds. A failed task is refunded; if your ledger only records the reservation, your numbers will drift from the invoice.

Before going to production

  • Use the exact origins: https://api.beatapi.io for tasks, files and capabilities, https://direct.beatapi.io for text calls.
  • Keep permanent keys server-side. Browsers get a short-lived Realtime client_secret, never an API key.
  • Store data.id and request_id before starting background work.
  • Poll with jitter; stop at terminal or action states.
  • Verify webhook signatures against raw bytes.
  • Record reservations, settlements, refunds, errors, and final output URLs, and download results within 72 hours of completion.
  • Alert on 402 — it stops every paid operation on the account at once.