spicyapiDocs
Main content

Errors

Every business code, its HTTP status, what to do about it, and which retries are worth making.

When a call goes wrong, the response tells you two things: a number (code) that says what kind of problem it is, and a sentence (msg) for a person to read. This page lists every number, what it means and whether trying again can help. If you only need a quick fix for a symptom, start with Troubleshooting.

The envelope

Native task API JSON responses use this envelope — the same four fields around every answer. Parse /v1 compatibility responses and SSE according to their own protocols:

{ "code": 200, "msg": "success", "data": { }, "request_id": "req_…" }
  • code is a business code, not an HTTP status. 200 means success.
  • On failure data is absent (not null) — you get code, msg and request_id. The one exception: a few asset library failures add data.reason.
  • msg is for humans: its wording can change, and so can its language (see below). Never branch on it; branch on code.
  • request_id is also returned in the X-Request-Id header. Quote it when reporting a problem.

The HTTP status is set correctly too. Branch on either — but only one: the two diverge on the specific codes (an insufficient balance is code: 40201 with HTTP 402), and mixing them means eventually missing a case.

We recommend branching on code. 404 can only say "not found"; 40201 says the available balance is insufficient.

Not every response is JSON

A response that doesn't parse as JSON — for example a plain-text or HTML page from our edge network — has no code. Handle it by HTTP status, log the first part of the body, and don't retry a 403 blindly: it may be a regional block that no retry will change.

Error message language

Human-readable error text can come back in the language you choose. The default is English. Only these three places follow that choice:

  • msg in the response envelope;
  • errorMessage on a failed task, in recordInfo and in webhook callbacks alike (with one exception, below);
  • error.message in the error objects of the compatible endpoints, whether they follow the OpenAI, Anthropic or Google Gemini (/v1beta) format.

Supported language codes: en, ja, ko, de, fr, es, pt-BR, ru, it, pl.

The exception: when the model itself gave a specific reason for failing — for example a reference image it could not read, or a copyright restriction on generated audio — errorMessage carries that reason in English, with internal details such as service names, hosts, URLs and request IDs removed, so you can see what actually went wrong. Reasons that mention account or billing state are never passed through; you get our own message instead. Content-Language still describes msg, and errorCode is always the value to branch on.

Choosing the language

The first of these that applies wins:

  1. The Accept-Language request header, for that request only. Standard HTTP weighting applies: we take the recognized language with the highest q value. Regional variants fold into their language — de-DE counts as de and pt-PT as pt-BR. Chinese is not offered, so every Chinese tag matches nothing and the next candidate is tried. * means no preference.
  2. Your account setting, under Settings → API error language in the console. It covers every request made with one of the account's API keys that carries no recognizable Accept-Language. Most server-side SDKs and curl send no such header by default, so this is the option most integrations rely on. Webhook callbacks have no request header to go on, so they always follow the account setting.
  3. Otherwise, English.

Error responses carry a Content-Language header naming the language the message was actually written in.

Only the human-readable text changes

code, errorCode, the OpenAI-compatible type and code, the Gemini-compatible code and status, and every field name stay the same in every language. Branch on codes and never parse the wording; record code and request_id in your logs and alerts.

Example

The same 40201 (insufficient balance) comes back in English by default:

Default
HTTP/1.1 402 Payment Required
Content-Language: en

{ "code": 40201, "msg": "Insufficient balance", "request_id": "req_…" }

Add one Accept-Language: ja header; the rest is the same create-task call as in the quickstart:

curl -X POST https://api.spicyapi.ai/api/v1/jobs/createTask \
  -H "Authorization: Bearer $SPICY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $SPICY_IDEMPOTENCY_KEY" \
  -H "Accept-Language: ja" \
  --data "$TASK_PAYLOAD"

msg is now Japanese; code is still 40201:

Accept-Language: ja
HTTP/1.1 402 Payment Required
Content-Language: ja

{ "code": 40201, "msg": "残高が不足しています", "request_id": "req_…" }

General codes

codeHTTPMeaningRetry?
200200Success—
400400Malformed request or invalid parametersNo. Fix and resend
40003400An uploaded file's size, type or content doesn't match what was declared when you requested the upload URLNo. Request a new upload URL with the correct contentType and size, upload again and commit
40004400The request is valid, but this model can't serve this combination of settings right nowNo. Change the setting named in msg (for example a resolution or aspect ratio), or choose another model. See below
401401Authentication failed; msg says which of three waysNo. Fix the header or the key
403403Not permitted. On an API call with a valid key, the account is restricted — see below. An unverified email address answers 40310 insteadNo
404404Does not exist (or is not yours)No
409409Conflicts with current stateSometimes — see below
40901409Quote expired, request changed or price changedQuote and confirm again; recover accepted requests with the original idempotency key
413413Request body exceeds the server's accepted size limitNo. Reduce the body or upload media through the media flow
429429Too many requestsUsually. Back off per Retry-After. One 429 is not about speed — see Rate limits
42901429The account already has its maximum number of media tasks running; no task was created and nothing was heldYes. Wait for a running task to finish and retry after Retry-After
500500Something broke on our sideYes. Back off and retry
503503A supporting service (quotes, inline image storage, media uploads) is briefly unavailableYes. Wait for Retry-After when it is present and retry — on createTask, with the same Idempotency-Key. If it persists without Retry-After, follow msg (for example use a public HTTPS URL instead of an inline image)

503 and 50301 share an HTTP status but are different business codes: 503 is about a supporting service, 50301 about the model itself.

Telling the three 401s apart

Three quite different mistakes all authenticate to 401, and they have different fixes. The code stays 401 in every case; msg is what tells them apart.

msg (English)What actually happenedWhat to change
Missing credentials: send your API key in the Authorization header as "Bearer sk-spicy-..." (on the compatible /v1 and /v1beta endpoints: …as "Authorization: Bearer sk-spicy-...", x-api-key, or x-goog-api-key)The request arrived carrying no credential at allYour client is dropping the header. Check the interceptor, the proxy, and whether the environment variable was loaded in the process that is running
API key format is not recognized: keys begin with sk-spicy-A credential arrived, but it is not one of oursYou pasted a console session value or another vendor's key. SpicyAPI keys start with sk-spicy-; echo "${SPICY_API_KEY:0:9}" should print exactly that
Credentials are invalid or expiredThe key is shaped like ours, but it doesn't exist, was revoked or has passed its expiry dateCheck the key on the API keys page; if it is revoked or expired, create a replacement. Retrying will never turn into a 200

The middle case is decided without a database lookup, which is why it can tell you something the third one cannot: it means the string never had a chance of working. The third message is deliberately identical for a key that doesn't exist, a revoked key and an expired key, so the answer can't be used to probe which keys exist.

These strings are shown in English here; msg follows the language selection described above, and its wording is not a contract. Branch on code, and treat the message as the thing you read, print or log — not the thing you match on.

Account cannot call the API

The key itself is valid in both of these cases; the account is what can't call the API yet.

40310 means the email address hasn't been verified. The message reads Verify your account email to run models and call the API…:

  1. Open the console. A banner at the top says the email address isn't verified and can send the verification email again.
  2. Follow the link in the verification email (check your spam folder).
  3. Retry the same call. No new key is needed.

The console itself keeps working while the API is blocked, so you can still see your history.

A plain 403 with This account cannot call the API right now means the account is restricted. Contact support with the request_id.

Balance and caps

codeHTTPMeaningWhat to do
40201402Balance does not cover the estimated costAdd funds under Billing in the console — see Account setup. Check GET /api/v1/chat/credit
40202402A spend limit was reachedRead msg to see which one. Key cap (This key has reached its …): raise it on the API keys page, or wait for the reset. Team limit (Workspace … budget has been reached): ask a team owner, admin or budget manager to raise it on the Team page. Platform cap (Platform quota for today is exhausted…): you can't change it; retry after 00:00 UTC. Daily caps restart at 00:00 UTC and monthly caps on the 1st at 00:00 UTC; a lifetime cap never resets

Neither is worth retrying — balances and caps do not change because you asked again. See Spend caps.

Permissions

codeHTTPMeaningWhat to do
40301403This key may not call this modelWiden the key's model allowlist in the console
40302403Source address is not on the key's IP allowlistAdd it, or drop the IP restriction on that key
40303403Service is not offered in this regionCannot be worked around. See where we operate
40310403The account's email address is not verified yet, so it cannot run modelsOpen the verification link from your sign-up email, or send a new one from the Console. The key works as soon as the address is verified, with no change on your side

None of these are retryable.

Asset library reason codes

Failures on the asset library endpoints (/api/v1/assets…) can add one machine-readable field, data.reason, to the usual envelope:

{ "code": 400, "msg": "…", "data": { "reason": "asset_library_locked" }, "request_id": "req_…" }

code, the HTTP status, msg and the task errorCode are the same with or without a reason, so existing handling keeps working. The reason appears only on the asset library endpoints, never on other native endpoints, and the OpenAI-compatible and other compatibility layers keep their own error shapes. The list may grow: treat a value you do not know like an absent reason.

data.reasonHTTPMeaningWhat to do
asset_library_locked400The asset library opens after the first top-upTop up. Assets you already saved stay usable
asset_library_full400The storage allowance (items or bytes) is fullDelete assets, or move up a plan; GET /api/v1/assets/usage shows the next one
asset_file_too_large400The file is above the plan's per-file limitUse a smaller file, or move up a plan
asset_daily_limit429The daily number of new assets is reachedWait until 00:00 UTC and honour Retry-After
asset_storage_full503Storage is full across the platformRetry later
asset_permission_denied403Your team role does not allow this changeAsk a team owner or admin, or use a key whose creator has a role that may
asset_workspace_forbidden403This key cannot reach that library, for example because the member who created the team key has left the teamCreate a new key in the workspace you need
asset_entity_name_taken409The library already has a character with that name (ignoring case). Characters are named on the Assets page of the web app, so the read-only API does not return it todayPick another name

Model availability

codeHTTPMeaningRetry?
50301503This model is currently unavailableYes. Retry later, or pick another model
50302503A text request (streaming or not) failed at the model before an answer was delivered; the hold was refundedYes. Resend with a new Idempotency-Key
40004400This model is running, but not with these settingsNo. Change the setting named in msg

50301 means the model could not accept the task at submission time: it is unlisted, has no active pricing, or has no generation capacity available right now. Temporary capacity issues may resolve with bounded retries. An unavailable model or missing active price will not be fixed by repeated requests. Refresh the catalog, and obtain user confirmation before switching models.

40004 and 50301 are deliberately different. 50301 means the model can't take any task right now — waiting may help. 40004 means the model is working but can't serve this combination of settings, and msg names the setting in parentheses, for example This model cannot serve this parameter combination right now (…). Waiting won't help; changing one value will. Neither creates a task or holds any money.

Generation failures after acceptance appear as state: failed

A generation failure after createTask has returned a task ID appears in recordInfo as state: "failed" with errorCode / errorMessage; the hold is normally released in full, except for certain content refusals explicitly disclosed as chargeable on the model page. The same situation as 40004, found only after acceptance, appears as errorCode: "unsupported_combination". Do not add synchronous business-code branches that are absent from this page.

Task failure codes

A failure after the task was accepted lands in errorCode on recordInfo. The set is closed: internal diagnostics never surface here, so handle any value outside this list as upstream_failed.

errorCodeMeaningRetry?
invalid_requestThe parameters were not acceptedNo. Fix them and submit again
unsupported_combinationThis combination is not supported right nowNo. Choose different settings
content_rejectedThe selected model declined this content. SpicyAPI itself doesn't review requests — see Content and usage responsibilityNo. Change the prompt, or choose a different model
rate_limitedThe generation service was busyYes. Back off and retry
upstream_unavailableGeneration is temporarily unavailableYes. Retry shortly
invalid_assetA reference asset is no longer availableNot as a retry. retry reuses the original input, so upload the asset again and create a new task with the new URI
generation_failedGeneration started and produced nothingMaybe. The same inputs will usually fail the same way
timeoutThe task passed its deadline unfinishedMaybe. Try a shorter duration or a lower resolution
upstream_failedCatch-all for anything elseYes. Back off and retry

Failed or expired tasks normally release the full hold. Some content refusals are charged at the accepted quote only when the model page explicitly discloses this exception. Check settled and cost for the final charge. errorMessage is for people: it states the reason in prose, may quote the model's own reason in English (see above), and its wording changes — branch on errorCode only. A "Retry" here means sending a new task, which is billed again if it succeeds.

Which errors cost money

Task state and connection state are different facts.

Explicitly rejected creations, expired tasks and historical canceled records incur no generation charge. Failed tasks are normally free, except for certain content refusals explicitly disclosed as chargeable on the model page. A client timeout or disconnect is not a task failure. Accepted tasks cannot be canceled: recover the original task and inspect its final state and settlement. A disconnected text stream may be billed when valid usage has already been recorded.

SituationCharged?
The API explicitly rejects createTask without creating a task (for example 40201, 40202, 40004 or 50301)No. Task creation and the hold share a transaction; a gateway error or missing response does not establish rejection
Submission times out, a tab closes or the connection dropsUnknown yet. Recover acceptance using the original idempotency key; do not treat this as a free retry
createTask returns 202, task later failed / expiredNormally no charge. Certain failed / content_rejected outcomes are charged at the accepted quote when the model page explicitly discloses this. Read settled and cost
A historical task is canceledNo. This is a compatibility state, not a currently available action
createTask returns 202, task succeededYes, settled on actual usage but capped at the accepted hold. Unused funds are released; no later amount is collected above the hold
Any error from recordInfo, chat/credit or common/*No. Those endpoints are never billed
Rate limited (429), or deduplicated by an idempotency keyNo. The first was never accepted; the second returns the original task, charged once

Settlement or release completes automatically, including after a process interruption. Ordinary failures release the full hold; certain content refusals explicitly disclosed on the model page are charged at the accepted quote. Check task settlement and balance to verify the outcome — see Billing.

When 409 is worth retrying

CaseRetry?
Rare concurrent createTask conflict with the same key and unchanged payloadYes. Back off a few hundred milliseconds and retry with the same key. See Idempotency
The same key was already used for another payload or API keyNo. Stop and fix key ownership; retrying cannot change the conflict
Inline images or an upload commit are still being processed (Retry-After may be present)Yes. Wait for Retry-After, or a couple of seconds, and resend with the same Idempotency-Key
Your account's pricing or configuration changed while the request was in flightYes. Quote again if you use quotes, then resend
Artefact still being copiedYes. Wait a few seconds and ask for the download link again
jobs/retry on a task that hasn't finished, or hasn't finished settlingYes, later. Wait until the source task is terminal and settled is true, then retry
jobs/retry on a succeeded task, or one whose input has already been removed under retentionNo. Create a new task with createTask
An upload URL or uploaded file has expiredNo. Upload the file again

Writing the retry

Do not retry blindly

400, 401, 40004, 40201 and similar input or authorization errors give the same answer however many times you ask. Every attempt marked "No" above is pure waste — and each one eats into your own rate limit.

Exponential backoff with jitter, so a batch of failures does not stampede back at the same instant:

JavaScript
// 409 is operation-specific and must be handled at the call site.
const RETRYABLE = new Set([429, 500, 503, 50301]);

async function callWithRetry(path, init, { attempts = 4 } = {}) {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch(`https://api.spicyapi.ai/api/v1${path}`, init);

    // A page from the edge network is not our JSON envelope
    if (!res.headers.get('content-type')?.includes('json')) {
      const text = await res.text();
      throw new Error(`HTTP ${res.status}, not JSON: ${text.slice(0, 200)}`);
    }
    const body = await res.json();

    if (body.code === 200) return body.data;
    if (!RETRYABLE.has(body.code)) {
      throw new Error(`${body.code} ${body.msg} (request_id=${body.request_id})`);
    }

    // When the server says how long to wait, trust it
    const retryAfter = Number(res.headers.get('retry-after'));
    const backoff = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000
      : 2 ** i * 1000 + Math.random() * 500;

    await new Promise((r) => setTimeout(r, backoff));
  }
  throw new Error('out of retries');
}
Python
import random, time, requests

# 409 is operation-specific and must be handled at the call site.
RETRYABLE = {429, 500, 503, 50301}
BASE = "https://api.spicyapi.ai/api/v1"


def call_with_retry(method: str, path: str, attempts: int = 4, **kwargs) -> dict:
    for i in range(attempts):
        res = requests.request(method, f"{BASE}{path}", **kwargs)

        # A page from the edge network is not our JSON envelope
        try:
            body = res.json()
        except ValueError:
            raise RuntimeError(f"HTTP {res.status_code}, not JSON: {res.text[:200]}")

        if body["code"] == 200:
            return body["data"]
        if body["code"] not in RETRYABLE:
            raise RuntimeError(f'{body["code"]} {body["msg"]} (request_id={body.get("request_id")})')

        # When the server says how long to wait, trust it
        retry_after = res.headers.get("retry-after")
        backoff = float(retry_after) if retry_after else 2**i + random.random() * 0.5
        time.sleep(backoff)

    raise RuntimeError("out of retries")
Go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

// retryable lists the codes worth another attempt. Anything else returns
// the same answer however many times you ask — and each ask eats your own
// rate limit.
// Whether the generation itself failed is read from recordInfo's state.
var retryable = map[int]bool{429: true, 500: true, 503: true, 50301: true}

type envelope struct {
	Code      int             `json:"code"`
	Msg       string          `json:"msg"`
	Data      json.RawMessage `json:"data"`
	RequestID string          `json:"request_id"`
}

func callWithRetry(newReq func() (*http.Request, error), attempts int, out any) error {
	for i := 0; i < attempts; i++ {
		req, err := newReq()
		if err != nil {
			return err
		}
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			// Transport-level failure: the request may well have arrived.
			// On createTask, send the same Idempotency-Key or this retry
			// turns into a second generation and a second charge.
			time.Sleep(backoff(i, ""))
			continue
		}

		var env envelope
		decErr := json.NewDecoder(res.Body).Decode(&env)
		io.Copy(io.Discard, res.Body)
		res.Body.Close()
		if decErr != nil {
			// Not our JSON envelope, for example a page from the edge network.
			return fmt.Errorf("HTTP %d, response is not JSON: %w", res.StatusCode, decErr)
		}

		if env.Code == 200 {
			return json.Unmarshal(env.Data, out)
		}
		if !retryable[env.Code] {
			return fmt.Errorf("%d %s (request_id=%s)", env.Code, env.Msg, env.RequestID)
		}
		// When the server says how long to wait, trust it
		time.Sleep(backoff(i, res.Header.Get("Retry-After")))
	}
	return fmt.Errorf("out of retries")
}

// backoff trusts Retry-After when present, otherwise backs off
// exponentially with jitter so a batch of failures does not come back
// as one thundering herd.
func backoff(attempt int, retryAfter string) time.Duration {
	if s, err := strconv.Atoi(retryAfter); err == nil && s > 0 {
		return time.Duration(s) * time.Second
	}
	base := time.Duration(1<<attempt) * time.Second
	return base + time.Duration(rand.Intn(500))*time.Millisecond
}

When retrying createTask, always send the same Idempotency-Key — otherwise "it actually succeeded, we just lost the response" becomes a duplicate generation and a duplicate charge.

Debugging

When an error makes no sense, work down this list:

  1. request_id — give us this and we can find the exact request.
  2. code — the tables above.
  3. Logs in the console — paste the task ID or request_id into the search box on the Logs page to open the task: status, cost, latency, the key that sent it, the error code and the reason. Request parameters and results are shown only while they are still retained, and in a team only to roles that may read content.

The msg for 500 is always a generic "service temporarily unavailable" with no internal detail: no internal structure, no component names, no stack traces ever appear in a response. Those can only be traced through request_id.

To reach us, open a conversation under Support in the console or email support@spicyapi.ai. Include the request_id or task ID, the time (UTC) and the code. Never send an API key.

On this page