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

# Swytcho API Error Codes and Troubleshooting Reference

> Understand every HTTP status code and error object the Swytcho API returns, and learn how to handle failures gracefully in your application.

Swytcho uses standard HTTP status codes to indicate whether a request succeeded or failed. Every error response includes a machine-readable JSON body so your code can branch on the specific problem, log the right context, and show a useful message to end users.

***

## Error Response Format

Every failed request returns a JSON object with an `error` field containing three properties.

```json Error response body theme={null}
{
  "error": {
    "type": "invalid_request_error",
    "message": "The value for 'temperature' must be between 0 and 2. You provided 5.",
    "code": "parameter_out_of_range"
  }
}
```

| Field           | Type   | Description                                                                        |
| --------------- | ------ | ---------------------------------------------------------------------------------- |
| `error.type`    | string | Broad category of the error (e.g. `invalid_request_error`, `authentication_error`) |
| `error.message` | string | Human-readable explanation of what went wrong                                      |
| `error.code`    | string | Machine-readable code identifying the specific error condition                     |

***

## HTTP Status Code Reference

| Status Code | Name                  | Cause                                                                               | Resolution                                                                                |
| ----------- | --------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `400`       | Bad Request           | The request body is malformed or missing required parameters                        | Validate your request payload against the [API reference](/api-reference)                 |
| `401`       | Unauthorized          | The API key is missing, malformed, or revoked                                       | Check that your `Authorization: Bearer <key>` header is present and the key is valid      |
| `403`       | Forbidden             | The API key does not have permission for the requested action or model              | Review the key's permissions in the [dashboard](https://app.swytcho.com)                  |
| `404`       | Not Found             | The requested model ID or resource does not exist                                   | Verify the model name against the [models list](/api-reference/models)                    |
| `422`       | Unprocessable Entity  | The JSON is valid but a field value is semantically invalid (e.g. `temperature: 5`) | Check parameter ranges and types in the [API reference](/api-reference)                   |
| `429`       | Too Many Requests     | You have exceeded your rate limit                                                   | Respect the `Retry-After` header and implement exponential backoff                        |
| `500`       | Internal Server Error | An unexpected error occurred on Swytcho's servers                                   | Retry with backoff; check [status.swytcho.com](https://status.swytcho.com) if it persists |
| `503`       | Service Unavailable   | Swytcho is temporarily down for maintenance or experiencing high load               | Wait and retry; monitor [status.swytcho.com](https://status.swytcho.com) for updates      |

***

## Common Error Types

<AccordionGroup>
  <Accordion title="authentication_error (401)">
    Your request did not include a valid API key. Make sure you are passing the key in the `Authorization` header as `Bearer YOUR_API_KEY`. Keys are available from the [API Keys page](https://app.swytcho.com/keys) in your dashboard.
  </Accordion>

  <Accordion title="invalid_request_error (400 / 422)">
    Something about the structure or values in your request is wrong. The `error.message` field describes the problem precisely — for example, a missing required field or a parameter value outside the allowed range.
  </Accordion>

  <Accordion title="rate_limit_error (429)">
    You have sent too many requests in a short window. Check the `Retry-After` response header for the number of seconds to wait before retrying. Implement exponential backoff to avoid hammering the API after the window resets.
  </Accordion>

  <Accordion title="server_error (500 / 503)">
    An error occurred on Swytcho's infrastructure. These are rare and typically transient. Retry the request with exponential backoff. If the problem persists for more than a few minutes, check [status.swytcho.com](https://status.swytcho.com) or contact support.
  </Accordion>
</AccordionGroup>

***

## Error Handling Best Practices

Follow these practices to make your integration resilient and easy to debug.

**Retry transient errors with backoff.** Network hiccups and `5xx` errors are often temporary. Retry up to three times using exponential backoff (e.g. wait 1 s, then 2 s, then 4 s) before surfacing an error to users.

**Never retry `4xx` errors blindly.** A `400`, `401`, `403`, or `422` indicates a problem with your request. Retrying without fixing the underlying issue wastes quota. Log the full error body and fix the root cause.

**Log `error.code` and `error.message`.** Store both fields in your application logs so you can debug production issues without reproducing them locally.

**Show user-friendly messages.** Translate API error codes into plain-language messages for end users — they should not see raw JSON or HTTP status codes.

<Warning>
  Do not log your API key or include it in bug reports. If you suspect a key has been exposed, rotate it immediately from the [dashboard](https://app.swytcho.com/keys).
</Warning>

***

## Code Examples

The examples below show a robust error-handling pattern for both official SDKs.

<CodeGroup>
  ```python Python SDK theme={null}
  from swytcho import Swytcho, APIStatusError, APIConnectionError

  client = Swytcho(api_key="YOUR_API_KEY")

  try:
      response = client.chat.completions.create(
          model="swytcho/gpt-4o",
          messages=[{"role": "user", "content": "Hello!"}],
      )
      print(response.choices[0].message.content)

  except APIStatusError as e:
      status = e.status_code

      if status == 401:
          print("Authentication failed. Check your API key.")
      elif status == 429:
          retry_after = e.response.headers.get("Retry-After", "unknown")
          print(f"Rate limit exceeded. Retry after {retry_after} seconds.")
      elif status == 422:
          print(f"Invalid request: {e.body['error']['message']}")
      elif status >= 500:
          print("Swytcho server error. Retrying with backoff...")
          # implement your retry logic here
      else:
          print(f"API error {status}: {e.body['error']['message']}")

  except APIConnectionError:
      print("Could not connect to Swytcho. Check your network.")
  ```

  ```typescript Node.js / TypeScript SDK theme={null}
  import Swytcho, { APIError } from "swytcho";

  const client = new Swytcho({ apiKey: process.env.SWYTCHO_API_KEY });

  async function callAPI() {
    try {
      const response = await client.chat.completions.create({
        model: "swytcho/gpt-4o",
        messages: [{ role: "user", content: "Hello!" }],
      });
      console.log(response.choices[0].message.content);
    } catch (err) {
      if (err instanceof APIError) {
        const { status, error } = err;

        if (status === 401) {
          console.error("Authentication failed. Check your API key.");
        } else if (status === 429) {
          const retryAfter = err.headers?.["retry-after"] ?? "unknown";
          console.error(`Rate limit exceeded. Retry after ${retryAfter} seconds.`);
        } else if (status === 422) {
          console.error(`Invalid request: ${error?.message}`);
        } else if (status >= 500) {
          console.error("Swytcho server error. Retrying with backoff...");
          // implement your retry logic here
        } else {
          console.error(`API error ${status}: ${error?.message}`);
        }
      } else {
        throw err; // re-throw non-API errors
      }
    }
  }

  callAPI();
  ```
</CodeGroup>

<Tip>
  Use a library like [tenacity](https://tenacity.readthedocs.io/) (Python) or [async-retry](https://github.com/vercel/async-retry) (Node.js) to add production-grade retry logic without writing it from scratch.
</Tip>
