> ## Documentation Index
> Fetch the complete documentation index at: https://docs.deapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Errors

> HTTP status codes and error responses returned by deAPI v2

deAPI uses conventional HTTP response codes to indicate the success or failure of an API request. Codes in the `2xx` range indicate success. Codes in the `4xx` range indicate an error from the provided information (e.g., missing required parameter, unauthorized access). Codes in the `5xx` range indicate an error with deAPI servers.

## HTTP Status Codes

| Code | Status | Description |
| - | - | - |
| `200` | OK | Request succeeded. Response contains requested data. |
| `401` | Unauthorized | Invalid or missing API key. |
| `403` | Forbidden | Account suspended. Returned before validation on endpoints that spend credits; `/price` endpoints are not gated. |
| `404` | Not Found | The requested resource (job, route) does not exist. |
| `413` | Payload Too Large | Request body exceeded the upload cap. See [Limits & Quotas](https://docs.deapi.ai/limits-and-quotas.md#file-uploads). |
| `422` | Unprocessable Entity | Request validation failed. Check the `errors` object for details. |
| `429` | Too Many Requests | Rate limit exceeded. |
| `500` | Internal Server Error | Something went wrong on our end. Try again later. |

## Error Response Format

Every error response carries a top-level `message`. Validation errors (`422`) additionally carry an `errors` object:

```json theme={null}
{
  "message": "The selected model does not exist.",
  "errors": {
    "model": ["The selected model does not exist."]
  }
}
```

**message** `string`

Human-readable error description. Present on every error response. For a `422` with several failures it summarises the first one and counts the rest, e.g. `"The width field must be at least 512. (and 2 more errors)"`.

**errors** `object`

**Only present on `422`.** A map of `field name → array of messages`, not an array. A single request can fail on several fields at once, and a single field can carry several messages.

> [!WARNING]
>
> The error body has **no `data` and no `statusCode` field** — read the status from the HTTP response itself. Do not iterate `errors` as an array: it is an object keyed by field name (`errors.model[0]`, not `errors[0].field`).

## Error Types

### 401 Unauthorized

Returned when authentication fails.

**Common causes:**

* Missing `Authorization` header
* Invalid API key
* Expired or revoked API key

```json theme={null}
{
  "message": "Unauthenticated."
}
```

**Solution:** Verify your API key is correct and included in the `Authorization: Bearer <API_KEY>` header.

***

### 404 Not Found

Returned when the requested resource doesn't exist. Two different bodies are possible.

**Unknown job / resource** — e.g. an invalid `request_id` when polling results:

```json theme={null}
{
  "message": "No query results for the requested resource."
}
```

> [!NOTE]
>
> Match on the **status code**, not on the message text. The wording of `404` messages is not part of the API contract and can change.

**Unknown route** — e.g. calling a documentation URL instead of the API path:

```json theme={null}
{
  "message": "The route api/v2/utilities/balance could not be found."
}
```

**Solution:** Verify the `request_id`, and take API paths from the [API Overview](https://docs.deapi.ai/api/v2/overview.md) — documentation URLs such as `/api/v2/utilities/balance` are not API routes (the real one is `/api/v2/account/balance`).

> [!NOTE]
>
> An unknown **model** is not a `404` — it fails validation and returns `422` with `errors.model`.

***

### 422 Unprocessable Entity

Returned when request validation fails. `errors` is an object keyed by field name.

**Common causes:**

* Missing required parameters
* Invalid parameter values (out of range, wrong type)
* A value outside the selected model's `info.limits`
* Invalid image/video URL or format

```json theme={null}
{
  "message": "The width field must be at least 512. (and 2 more errors)",
  "errors": {
    "width": ["The width field must be at least 512."],
    "height": ["The height field must be at least 512."],
    "steps": ["The steps field must be at least 8."]
  }
}
```

**Solution:** Iterate the keys of the `errors` object to identify which fields failed and correct them. Many limits are model-specific — read `info.limits` from the [Model Selection](https://docs.deapi.ai/api/v2/utilities/models.md) endpoint for the model you are calling.

***

### 429 Too Many Requests

Returned when you exceed your rate limit.

```json theme={null}
{
  "message": "Too Many Attempts."
}
```

Every response carries the current allowance in headers:

| Header | Meaning |
| - | - |
| `X-RateLimit-Limit` | Requests allowed in the current window |
| `X-RateLimit-Remaining` | Requests left in the current window |
| `X-RateLimit-Source` | Which limit bucket was applied |

**Solution:** Back off and retry — see [Limits & Quotas](https://docs.deapi.ai/limits-and-quotas.md#rate-limit-errors).

***

### 500 Internal Server Error

Returned when an unexpected error occurs on our servers.

```json theme={null}
{
  "message": "Server Error"
}
```

**Solution:** Wait a moment and retry your request. If the problem persists, check [status.deapi.ai](https://status.deapi.ai/) or contact support on [Discord](https://discord.com/invite/UFfK5YRBsr).

> [!NOTE]
>
> A job that fails **after** it was accepted does not produce an HTTP error. The submission returns `200` with a `request_id`, and the failure surfaces on the job status as `status: "error"` with `error_code`, `error_reason`, `retryable` and `refunded`. See [Webhooks](https://docs.deapi.ai/execution-modes-and-integrations/webhooks.md) for the full value lists.

## Best Practices

> [card] Handle all error codes
>
> Implement error handling for all possible status codes in your application.

> [card] Parse the errors object
>
> For 422 responses, iterate the keys of the `errors` object to display field-specific messages to users.

> [card] Implement retry logic
>
> For 500 errors, implement exponential backoff retry (e.g., 1s, 2s, 4s delays).

> [card] Log error responses
>
> Log full error responses for debugging. Include `request_id` if available.

## Example Error Handling

```python Python theme={null}
import requests

response = requests.post(
    "https://api.deapi.ai/api/v2/images/generations",
    headers={
        "Authorization": "Bearer YOUR_API_KEY",
        "Accept": "application/json"
    },
    json={
        "prompt": "a cat",
        "model": "Flux1schnell",
        "width": 512,
        "height": 512,
        "steps": 4,
        "guidance": 0,
        "seed": -1,
        "loras": []
    }
)

if response.status_code == 200:
    data = response.json()
    request_id = data["data"]["request_id"]
    print(f"Job started: {request_id}")
elif response.status_code == 401:
    print("Authentication failed. Check your API key.")
elif response.status_code == 422:
    error_data = response.json()
    print(f"Validation error: {error_data['message']}")
    # `errors` is an object: field name -> list of messages
    for field, messages in error_data.get("errors", {}).items():
        print(f"  Field '{field}': {messages}")
elif response.status_code == 429:
    print("Rate limited. Remaining:", response.headers.get("X-RateLimit-Remaining"))
elif response.status_code == 500:
    print("Server error. Retrying...")
else:
    print(f"Unexpected error: {response.status_code}")
```

```javascript JavaScript theme={null}
const response = await fetch("https://api.deapi.ai/api/v2/images/generations", {
  method: "POST",
  headers: {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
    "Accept": "application/json"
  },
  body: JSON.stringify({
    prompt: "a cat",
    model: "Flux1schnell",
    width: 512,
    height: 512,
    steps: 4,
    guidance: 0,
    seed: -1,
    loras: []
  })
});

if (response.ok) {
  const data = await response.json();
  const requestId = data.data.request_id;
  console.log(`Job started: ${requestId}`);
} else if (response.status === 401) {
  console.error("Authentication failed. Check your API key.");
} else if (response.status === 422) {
  const errorData = await response.json();
  console.error(`Validation error: ${errorData.message}`);
  // `errors` is an object: field name -> array of messages
  for (const [field, messages] of Object.entries(errorData.errors ?? {})) {
    console.error(`  Field '${field}': ${messages.join(", ")}`);
  }
} else if (response.status === 429) {
  console.error("Rate limited. Remaining:", response.headers.get("X-RateLimit-Remaining"));
} else if (response.status === 500) {
  console.error("Server error. Retrying...");
} else {
  console.error(`Unexpected error: ${response.status}`);
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.