# Errors

> Error envelope format and full status-code reference.

Datapoint uses conventional HTTP status codes. Most endpoints return a consistent JSON envelope on error, with a couple of exceptions noted below.

## Error envelope

Most non-2xx responses have the same shape:

```json
{
  "detail": "<human-readable message or structured error data>",
  "message": "<mirror of detail>"
}
```

- **`detail`**: for simple errors, a string; for validation errors (`422`), an array of field-level error objects; for `402 Payment Required` and any error that carries a `code` field (content review, oversized media, unsupported media), an object.
- **`message`**: a mirror of `detail` for most errors, with one deliberate exception — on a field-validation `422`, `detail` is the array of field errors while `message` is a joined summary string. It is a plain string for simple errors and every `500`. When `detail` is an object (e.g. `402`, a content-review block, or a rejected plan — the latter two are also `422`s), `message` holds that same object, **not** a string.

<DocCallout type="warning" title="Coerce message before logging">
Because `message` mirrors `detail`, it is not guaranteed to be a string. Coerce it (e.g. `str(message)` / `String(message)`) before writing it to a log line or surfacing it in a UI that expects text.
</DocCallout>

<DocCallout type="note" title="Not every route uses the envelope">
The media proxy streams binary content and replies with a bare status code and headers — no JSON body — for `403`, `404`, `416`, and `502`, and returns `206` (partial content, range request) and `304` (not modified) as success responses. A shared report link returns JSON on success and a bare `403` for any signature or lookup failure — it never returns `404`. Branch on the status code, not on a parsed body, when consuming either.
</DocCallout>

## Status codes

| Code | Meaning | Typical cause |
|---|---|---|
| `400` | Bad Request | Missing or invalid field that doesn't fit field-level validation (e.g. `dimensions` and `instruction` both set, or a missing `datapoints` array); unknown `task_type`; handler-level datapoint rejection; unsupported or mismatched media; content-review `invalid_media`. Some `400`s carry a `code` object. |
| `401` | Unauthorized | Missing, malformed, or inactive API key (e.g. `"Invalid or inactive API key"`). Dashboard-managed endpoints also return `401` when their credential is missing or invalid. The exact message varies by cause. |
| `402` | Payment Required | Not enough account credits to cover the charge (job reservation or planner fee). `detail` is an object with `needed_credits` and `available_credits`. |
| `403` | Forbidden | Signed media-URL signature invalid or not authorized for the requested resource. Returned as a bare status by the media proxy. |
| `404` | Not Found | Job, media, or API key doesn't exist (or belongs to another client). The media proxy returns a bare `404`. |
| `409` | Conflict | Duplicate invite — a pending invite already exists for the email, or the email already belongs to your organization. Also a job created under a name one of your streams already holds (`name_conflict`), and the reverse on `POST /streams`; streams answer other `409`s too, each with a `code` (see [Streams errors](/docs/api/streams#errors)). (Re-submitting a job with a name one of your jobs already uses is **not** a conflict; it returns `200` with the existing job.) |
| `410` | Gone | A one-time code (e.g. device authorization) has expired or already been used. |
| `413` | Payload Too Large | An uploaded media file exceeds the size limit. `detail` is an object: `{"code": "media_too_large", "max_bytes": ...}`. |
| `422` | Unprocessable Entity | Field-level request validation failed. `detail` is an array of per-field errors. Content-review blocks also surface here (see [Content review](#content-review)). |
| `429` | Too Many Requests | Rate limit exceeded. The actionable signal is the `Retry-After` header (seconds until the window resets). |
| `500` | Internal Server Error | Unexpected server error. `detail` and `message` are usually the string `"Internal Server Error"`; a few handled failures return `500` with a more specific string. |
| `502` | Bad Gateway | The planner could not produce a plan. The media proxy also returns a bare `502` on an upstream storage error. |
| `503` | Service Unavailable | Task dispatch failed (retry with a new `name`), or content review is temporarily unavailable (a `Retry-After` header is set). |
| `504` | Gateway Timeout | The planner timed out. |

## Examples

### 400: task-type rejection

Sent back when a task handler rejects your payload shape (e.g. a comparison datapoint with 3 candidates instead of 2):

```json
{
  "detail": "Datapoint 0: comparison requires exactly 2 media items under 'candidates', got 3.",
  "message": "Datapoint 0: comparison requires exactly 2 media items under 'candidates', got 3."
}
```

### 402: insufficient balance

`detail` is an object carrying the shortfall in credits so you can show a clear message to your user. Because `message` mirrors `detail`, it holds the **same object** — not a string. The `message` string inside the object varies by endpoint (`"Insufficient balance"` for jobs; `"Insufficient balance for planner fee"` for the planner), but `needed_credits` / `available_credits` are always present.

```json
{
  "detail": {
    "message": "Insufficient balance",
    "needed_credits": 150,
    "available_credits": 75
  },
  "message": {
    "message": "Insufficient balance",
    "needed_credits": 150,
    "available_credits": 75
  }
}
```

Top up via `POST /billing/checkout` and retry.

### 422: request validation

Field-level validation emits one entry per offending field. The `message` summary joins those entries with `"; "`, and each entry's location path is joined with `" -> "` (the leading `body` segment is dropped):

```json
{
  "detail": [
    {
      "type": "missing",
      "loc": ["body", "name"],
      "msg": "Field required"
    },
    {
      "type": "string_type",
      "loc": ["body", "response_options", 0],
      "msg": "Input should be a valid string"
    }
  ],
  "message": "name: Field required; response_options -> 0: Input should be a valid string"
}
```

### 429: rate limit

```json
{
  "detail": "Rate limit exceeded",
  "message": "Rate limit exceeded"
}
```

Read the `Retry-After` header to know how long to back off. See [Rate limits](/docs/rate-limits) for details.

### 503: dispatch failed

When background task dispatch is unreachable:

```json
{
  "detail": "Failed to queue tasks. Please retry with a new name.",
  "message": "Failed to queue tasks. Please retry with a new name."
}
```

The job's reservation has already been released, so retrying with a new `name` is safe and won't double-charge.

## Content review

Uploaded media pass through an automated content-review step at upload time, before any job can use them. Media referenced by URL are reviewed while the job's datapoints are processed, after the job is accepted — a block there marks that datapoint as blocked (visible in `errors` on `GET /jobs/{job_id}`) instead of failing the request. Three outcomes surface as request errors:

| Code | `detail.code` | Meaning |
|---|---|---|
| `422` | `content_blocked` | The media did not pass content review and cannot be used. |
| `400` | `invalid_media` | The media could not be reviewed because it was unreadable or malformed (corrupt file, wrong format). |
| `503` | — | Content review is temporarily unavailable. A `Retry-After` header tells you when to retry. |

A blocked upload looks like:

```json
{
  "detail": {
    "code": "content_blocked",
    "filename": "clip.mp4",
    "reason": "This content did not pass moderation review."
  },
  "message": {
    "code": "content_blocked",
    "filename": "clip.mp4",
    "reason": "This content did not pass moderation review."
  }
}
```

For `content_blocked` (`422`) and `invalid_media` (`400`), fix or replace the offending file and resubmit. For the `503` case, wait for the interval in `Retry-After` and retry the same request — it is safe to repeat.

## Handling errors

A minimal handling pattern:

<CodeTabs>
  <CodeTab lang="python" label="Python">
```python
r = requests.post(url, headers=headers, json=body)
if r.status_code == 402:
    short = r.json()["detail"]
    raise RuntimeError(
        f"Top up {short['needed_credits'] - short['available_credits']} credits to continue"
    )
if r.status_code in (429, 503):
    time.sleep(int(r.headers.get("Retry-After", 60)))
    # retry
r.raise_for_status()
```
  </CodeTab>
  <CodeTab lang="node" label="Node.js">
```javascript
const res = await fetch(url, options);
if (res.status === 402) {
  const { detail } = await res.json();
  throw new Error(
    `Top up ${detail.needed_credits - detail.available_credits} credits`
  );
}
if (res.status === 429 || res.status === 503) {
  const wait = parseInt(res.headers.get("Retry-After") ?? "60", 10);
  await new Promise((r) => setTimeout(r, wait * 1000));
  // retry
}
if (!res.ok) throw new Error(await res.text());
```
  </CodeTab>
</CodeTabs>

## Next

- [Rate limits](/docs/rate-limits): 429 handling in depth
- [Billing](/docs/billing): how costs are reserved and refunded
