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

# Error Codes

> What each Sorsa API status code means, what causes it, and how to fix it, from 400 to 500.

When a request fails, Sorsa returns a standard HTTP status code and a JSON body with a `message` field describing the problem. This page covers every code you may encounter, what causes it, and how to resolve it.

## Error response format

All error responses share the same structure:

```json theme={null}
{
  "message": "ApiKey required"
}
```

The `message` field is a human-readable description of what went wrong. Check it first when debugging; it often points straight at the problem.

## Quick reference

| Code | Type         | Meaning                                          |
| :--- | :----------- | :----------------------------------------------- |
| 200  | Success      | Request completed successfully                   |
| 400  | Client error | Bad request: invalid or missing parameters       |
| 401  | Client error | Unauthorized: authentication failed              |
| 403  | Client error | Forbidden: valid key but no access or credits    |
| 404  | Client error | Not found: resource does not exist or is private |
| 429  | Client error | Too many requests: rate limit exceeded           |
| 500  | Server error | Internal error: something went wrong on our side |

## 400 Bad Request

The request could not be processed because of invalid or missing parameters.

**Common causes**

* A required parameter is missing (for example, `link`, `id`, `username`, or `query`)
* A parameter has the wrong type or format (for example, a string where a number is expected)
* The JSON body in a POST request is malformed or empty

**How to fix:** Check the [API Reference](https://docs.sorsa.io/api-reference-guide) for the endpoint you are calling and confirm every required parameter is present and correctly formatted. For POST requests, set `Content-Type: application/json` and make sure the body is valid JSON.

## 401 Unauthorized

Authentication failed. The API could not identify your account.

**Common causes**

* The `ApiKey` header is missing entirely
* The header name is misspelled. It is case-sensitive: use `ApiKey`, not `Api-Key`, `apikey`, or `api_key`
* The key value is wrong, was copied with extra whitespace, or belongs to a deleted key

**How to fix:** Confirm your request sends the header exactly as `ApiKey: your_key_here`, and check that the key is still active in your [Dashboard](https://api.sorsa.io/overview/keys). When in doubt, copy the key straight from the dashboard. See [Authentication](https://docs.sorsa.io/authentication) for more.

## 403 Forbidden

Your API key is valid, but the request was rejected.

**Common causes**

* Your request quota is exhausted (0 requests remaining)
* Your subscription has expired

**How to fix:** Check your remaining balance with `GET /key-usage-info` or in your [Dashboard](https://api.sorsa.io/overview). If your requests are used up, top up or upgrade on the [Billing](https://api.sorsa.io/overview/billing) page.

## 404 Not Found

The requested resource does not exist.

**Common causes**

* The X user changed their username, deleted their account, or was suspended
* The tweet was deleted by its author
* The account or tweet is private (protected). Sorsa can only access public data
* The endpoint URL itself is incorrect

**How to fix:** Confirm the user or tweet still exists and is publicly accessible on X. If you are using a user ID, check that it has not been reassigned. If you are using a username, the account may have changed it; resolve the current mapping with `/username-to-id`.

## 429 Too Many Requests

You have exceeded the rate limit of 20 requests per second.

**Common causes**

* Sending requests in a tight loop with no delay
* Running multiple parallel workers that share one API key

**How to fix:** Add a small delay between requests (a 50ms pause holds you at the 20 req/s limit) or add retry logic with a one-second pause. See [Rate Limits](https://docs.sorsa.io/rate-limits) for strategies and code examples.

## 500 Internal Server Error

Something went wrong on our side.

**What to do**

* Retry after a short delay (1 to 2 seconds). Transient 500s often clear on their own.
* If it persists across retries or affects multiple endpoints, check the [Status Page](https://uptime.sorsa.io/status/v3) for ongoing incidents.
* If the problem continues, contact support at [contacts@sorsa.io](mailto:contacts@sorsa.io) or on [Discord](https://discord.com/invite/uwAefKCj7X) with the endpoint URL, request body, and approximate timestamp.

## Handling errors in code

A resilient integration handles every error code gracefully instead of crashing on an unexpected response. Here is a reusable pattern for Python and JavaScript.

**Python**

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

def sorsa_request(method, endpoint, api_key, params=None, json_body=None, max_retries=3):
    url = f"https://api.sorsa.io/v3{endpoint}"
    headers = {"ApiKey": api_key}

    for attempt in range(max_retries):
        if method == "GET":
            response = requests.get(url, headers=headers, params=params)
        else:
            response = requests.post(url, headers=headers, json=json_body)

        if response.status_code == 200:
            return response.json()

        if response.status_code == 429:
            time.sleep(1)
            continue

        if response.status_code == 500:
            time.sleep(2)
            continue

        # Non-retryable errors: 400, 401, 403, 404
        error_msg = response.json().get("message", "Unknown error")
        raise Exception(f"{response.status_code}: {error_msg}")

    raise Exception("Max retries exceeded")


# Usage
data = sorsa_request("GET", "/info", "YOUR_API_KEY", params={"username": "elonmusk"})
print(data["display_name"])
```

**JavaScript**

```javascript theme={null}
async function sorsaRequest(method, endpoint, apiKey, body = null, maxRetries = 3) {
  const url = `https://api.sorsa.io/v3${endpoint}`;
  const options = {
    method,
    headers: { "ApiKey": apiKey },
  };

  if (body) {
    options.headers["Content-Type"] = "application/json";
    options.body = JSON.stringify(body);
  }

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 200) {
      return await response.json();
    }

    if (response.status === 429) {
      await new Promise((r) => setTimeout(r, 1000));
      continue;
    }

    if (response.status === 500) {
      await new Promise((r) => setTimeout(r, 2000));
      continue;
    }

    // Non-retryable errors: 400, 401, 403, 404
    const data = await response.json();
    throw new Error(`${response.status}: ${data.message || "Unknown error"}`);
  }

  throw new Error("Max retries exceeded");
}

// Usage
const data = await sorsaRequest("GET", "/info?username=elonmusk", "YOUR_API_KEY");
console.log(data.display_name);
```

The idea: retry on `429` and `500` (transient), but fail fast on `400`, `401`, `403`, and `404` (these need a code or configuration fix).

## Next steps

* [Rate Limits](https://docs.sorsa.io/rate-limits) - Strategies for staying within the 20 req/s limit
* [Pagination](https://docs.sorsa.io/pagination) - Fetch large datasets without errors
* [API Reference](https://docs.sorsa.io/api-reference-guide) - Full endpoint list with parameter schemas
