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

# HTTP status codes & errors

> ButterCMS API HTTP status codes: 2xx for success, 400 validation, 401 unauthorized, 404 not found, 429 rate limit exceeded, and 500 for server errors.

## Status code summary

| Code  | Status                | Description                                                                    |
| ----- | --------------------- | ------------------------------------------------------------------------------ |
| `200` | OK                    | Request succeeded                                                              |
| `202` | Accepted              | Request accepted for processing (write operations)                             |
| `204` | No Content            | Request succeeded, no content returned (deletions)                             |
| `400` | Bad Request           | Invalid request parameters or data                                             |
| `401` | Unauthorized          | Missing or invalid authentication                                              |
| `403` | Forbidden             | Insufficient permissions or invalid collection filter/order                    |
| `404` | Not Found             | Requested resource does not exist                                              |
| `405` | Method Not Allowed    | HTTP method not supported for endpoint                                         |
| `429` | Too Many Requests     | Monthly API call limit exceeded (Free/Trial)                                   |
| `500` | Internal Server Error | Server error ([contact support](../../support/contact-status/contact-support)) |

## Success responses

### 200 OK

Standard success response for read operations. The response body contains the requested data.

```json theme={null}
{
  "meta": {
    "count": 10,
    "next_page": 2,
    "previous_page": null
  },
  "data": [
    // Content items...
  ]
}
```

### 202 Accepted

Returned for write operations (POST, PUT, PATCH). The request has been accepted for asynchronous processing, with background tasks handling media uploads, validation, and webhook notifications.

```json theme={null}
{
  "status": "pending"
}
```

### 204 No Content

Returned for successful DELETE operations. No response body is included.

## Error responses

All error responses follow a consistent format:

```json theme={null}
{
  "detail": "Error message describing what went wrong"
}
```

### 400 Bad Request

Indicates invalid request parameters or validation errors.

**Field-Specific Validation Errors:**

```json theme={null}
{
  "title": ["You must specify a page title."],
  "slug": ["You must specify a page slug."]
}
```

**General Error Message:**

```json theme={null}
{
  "error": "Cannot create a new Collection Item. Collection Item Limit Reached."
}
```

{/* SOURCE: file_path="api-documentation/openapi/paths/collections/collection-detail.yaml" section="400" */}

**Common 400 Error Causes:**

| Error                    | Description                             | Solution                             |
| ------------------------ | --------------------------------------- | ------------------------------------ |
| Invalid locale           | Locale not configured on account        | Check configured locales in Settings |
| Invalid levels parameter | levels must be 1-5                      | Use integer between 1 and 5          |
| Missing required field   | Required field not provided             | Include all required fields          |
| Invalid field format     | Field value doesn't match expected type | Check field type requirements        |

**Example Errors:**

```json theme={null}
// Invalid locale (read operations)
{
  "locale": "The passed locale isn't configured on this account."
}

// Invalid locale (write operations)
{
  "fields": "Locales were specified without being configured on your account: 'xyz'."
}

// Invalid levels parameter
{
  "detail": "levels query parameter should be an integer between 1 and 5 (inclusive)"
}
```

### 401 Unauthorized

Authentication credentials are missing or invalid.

**Missing token:**

```json theme={null}
{
  "detail": "Authentication credentials were not provided"
}
```

**Invalid token:**

```json theme={null}
{
  "detail": "Invalid token."
}
```

**Inactive or expired token:**

```json theme={null}
{
  "detail": "Token inactive."
}
```

```json theme={null}
{
  "detail": "Token expired."
}
```

**Common Causes:**

| Cause                                 | Solution                                                                                |
| ------------------------------------- | --------------------------------------------------------------------------------------- |
| Missing `auth_token` parameter        | Add `?auth_token=YOUR_TOKEN` to URL                                                     |
| Missing Authorization header          | Add `Authorization: Token YOUR_TOKEN` header                                            |
| Invalid API token                     | Check token in ButterCMS Settings                                                       |
| Token inactive or expired             | [Contact support](../../support/contact-status/contact-support) or generate a new token |
| Using Read token for Write operations | Request a Write API token                                                               |

<Warning>
  The API token you use for reading will not allow write operations. Contact [support@buttercms.com](mailto:support@buttercms.com) to request a Write API token.
</Warning>

### 403 Forbidden

The authentication is valid, but the request is not permitted. This includes permission errors and invalid query parameters when filtering or ordering collections.

```json theme={null}
{
  "detail": "You do not have permission to perform this action."
}
```

**Invalid filter key (collections):**

```json theme={null}
{
  "detail": "Invalid filter key nonexistent_field"
}
```

**Common Causes:**

* Using an invalid field name to filter or order collection results
* Attempting to access content from a different organization
* Feature not enabled for your account

### 404 Not Found

The requested resource doesn't exist.

```json theme={null}
{
  "detail": "Not found."
}
```

**Common Causes:**

| Cause                  | Example                                | Solution                |
| ---------------------- | -------------------------------------- | ----------------------- |
| Invalid page slug      | `/pages/blog/nonexistent-post/`        | Check slug spelling     |
| Invalid page type      | `/pages/invalid-type/page-slug/`       | Verify page type exists |
| Invalid collection key | `/content/invalid-collection/`         | Check collection key    |
| Invalid item ID        | `/content/artists/99999/`              | Verify item ID exists   |
| Invalid pagination     | `?page=999` (when only 10 pages exist) | Check total page count  |

**Pagination Error:**

```json theme={null}
{
  "detail": "Invalid Page."
}
```

### 405 Method Not Allowed

The HTTP method is not supported for the endpoint.

```json theme={null}
{
  "detail": "Method \"DELETE\" not allowed."
}
```

**Solution:** Check the [REST Endpoints reference](../concepts/rest-endpoints-urls) for supported methods.

### 429 Too Many Requests

Your account has been temporarily blocked after exceeding its monthly API call limit (Free/Trial accounts).

```json theme={null}
{
  "detail": "API Calls limit reached."
}
```

See [Rate Limits & Throttling](../concepts/rate-limits-throttling) for details on limits and how to recover.

### 500 Internal Server Error

An error occurred on ButterCMS servers.

```json theme={null}
{
  "detail": "Internal server error"
}
```

If you receive this error:

1. Wait a moment and retry the request
2. Check [ButterCMS Status](https://status.buttercms.com/) for any incidents
3. Contact [support@buttercms.com](mailto:support@buttercms.com) if the issue persists

## Error handling best practices

### JavaScript / Node.js

```javascript theme={null}
async function fetchFromButter(endpoint) {
  try {
    const response = await fetch(
      `https://api.buttercms.com/v2${endpoint}?auth_token=${API_TOKEN}`
    );

    if (!response.ok) {
      const error = await response.json();

      switch (response.status) {
        case 400:
          console.error('Validation error:', error);
          // Handle validation errors
          break;
        case 401:
          console.error('Authentication failed:', error.detail);
          // Redirect to login or refresh token
          break;
        case 404:
          console.error('Resource not found:', error.detail);
          // Show 404 page or fallback content
          break;
        case 429:
          console.error('API limit reached:', error.detail);
          // Respect Retry-After and wait until the monthly reset
          break;
        default:
          console.error('API error:', error);
      }

      throw new Error(error.detail || 'API request failed');
    }

    return await response.json();
  } catch (error) {
    console.error('Network error:', error);
    throw error;
  }
}
```

### Python

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

def fetch_from_butter(endpoint, retries=3):
    url = f"https://api.buttercms.com/v2{endpoint}"

    for attempt in range(retries):
        try:
            response = requests.get(
                url,
                params={'auth_token': API_TOKEN}
            )

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

            elif response.status_code == 400:
                error = response.json()
                raise ValueError(f"Validation error: {error}")

            elif response.status_code == 401:
                raise PermissionError("Authentication failed")

            elif response.status_code == 404:
                raise FileNotFoundError("Resource not found")

            elif response.status_code == 429:
                retry_after = response.headers.get("Retry-After")
                raise RuntimeError(f"API limit reached. Retry after {retry_after} seconds.")

            else:
                response.raise_for_status()

        except requests.RequestException as e:
            if attempt == retries - 1:
                raise
            sleep(1)

    raise Exception("Max retries exceeded")
```

### Exponential backoff pattern

For transient errors (5xx), implement exponential backoff:

```javascript theme={null}
async function fetchWithRetry(endpoint, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetchFromButter(endpoint);
      return response;
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;

      // Exponential backoff: 1s, 2s, 4s, 8s...
      const waitTime = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}
```

## Webhook error responses

When your webhook endpoint receives notifications from ButterCMS:

| Your Response        | ButterCMS Behavior                |
| -------------------- | --------------------------------- |
| `2xx`                | Webhook delivered successfully    |
| Non-`2xx` or timeout | Webhook delivery logged as failed |

<Info>
  Webhook endpoints must respond within 5 seconds. Requests that exceed this timeout will be treated as failures.
</Info>

## Next steps

<CardGroup cols={2}>
  <Card title="Rate Limits" icon="gauge-high" href="../concepts/rate-limits-throttling">
    Learn about API rate limits
  </Card>

  <Card title="Authentication" icon="key" href="../concepts/authentication-api-tokens">
    Fix authentication issues
  </Card>

  <Card title="Request Format" icon="code" href="../concepts/request-response-format">
    Review request requirements
  </Card>
</CardGroup>
