> ## 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.

# API error codes

> A detailed reference for all possible ButterCMS API error codes and how to resolve them.

## HTTP status codes overview

| Status Code                 | Category     | Description                                  |
| --------------------------- | ------------ | -------------------------------------------- |
| `200 OK`                    | Success      | Request succeeded, data returned             |
| `202 Accepted`              | Success      | Write request accepted for processing        |
| `400 Bad Request`           | Client Error | Invalid request parameters                   |
| `401 Unauthorized`          | Client Error | Authentication failed                        |
| `403 Forbidden`             | Client Error | Access denied or resource conflict           |
| `404 Not Found`             | Client Error | Resource doesn't exist                       |
| `429 Too Many Requests`     | Client Error | Monthly API call limit exceeded (Free/Trial) |
| `500 Internal Server Error` | Server Error | Server-side issue                            |

***

## Authentication errors (401)

### Missing API token

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

**Cause:** No API token was included in the request.

**Solution:** Include your API token either as:

* Query parameter: `?auth_token=YOUR_TOKEN`
* Authorization header: `Authorization: Token YOUR_TOKEN`

### Invalid API token

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

**Cause:** The provided API token is incorrect or has been revoked.

**Solution:**

1. Go to Settings > API Tokens in your dashboard
2. Copy the correct Read API Token
3. Ensure there are no extra spaces or characters

### Write token required

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

**Cause:** Attempting to create/update content with a Read API token.

**Solution:** Write operations require a Write API Token. Contact [support@buttercms.com](mailto:support@buttercms.com) to request write access.

***

## Bad request errors (400)

### Invalid query parameters

```json theme={null}
{
  "detail": "levels query parameter should be an integer between 1 and 5 (inclusive)"
}
```

**Cause:** Query parameter value is out of valid range or wrong type.

**Solution:** Check the API documentation for valid parameter values:

* `levels`: Integer 1-5
* `page`: Positive integer
* `page_size`: Integer 1-100

### Invalid locale parameter

```json theme={null}
{
  "detail": "Invalid locale parameter"
}
```

**Cause:** The specified locale doesn't exist or is not enabled.

**Solution:**

1. Go to Settings > Localization in your dashboard
2. Verify the locale slug matches your API request
3. Locale slugs are typically lowercase (e.g., `en`, `es`, `fr-ca`)

### Invalid search parameters

```json theme={null}
{
  "detail": "Invalid search query"
}
```

**Cause:** Search query is malformed or contains invalid characters.

**Solution:** Ensure search queries:

* Are URL-encoded if containing special characters
* Don't exceed maximum length (typically 256 characters)
* Use valid search syntax

### Invalid field filter

```json theme={null}
{
  "detail": "Invalid fields parameter"
}
```

**Cause:** Requested fields don't exist or have invalid syntax.

**Solution:** Check that:

* Field names match your content schema exactly
* Use dot notation for nested fields: `fields.hero.title`
* Fields parameter is comma-separated without spaces

***

## Forbidden errors (403)

### Multiple pages found

```json theme={null}
{
  "detail": "Multiple pages found for the given slug"
}
```

**Cause:** When using `page_type=*`, multiple pages share the same slug.

**Solution:**

1. Specify a page type instead of `*`: `/pages/landing_page/homepage`
2. Or ensure slugs are unique across all page types

### Access Denied

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

**Cause:** Your account or API token doesn't have access to this resource.

**Solution:**

* Verify you're using the correct account's API token
* Check if your plan includes access to this feature
* [Contact support](../contact-status/contact-support) if you believe this is an error

***

## Not found errors (404)

### Page not found

```json theme={null}
{
  "detail": "Page matching query does not exist"
}
```

**Cause:** No page exists with the specified page type and slug.

**Solution:**

1. Verify the page is published (not draft)
2. Check the slug matches exactly (case-sensitive)
3. Confirm the page type key is correct
4. Verify the page exists in the dashboard

### Collection not found

```json theme={null}
{
  "detail": "Collection matching query does not exist"
}
```

**Cause:** The collection key doesn't exist.

**Solution:**

1. Check the collection key in Content Types > Collections
2. Collection keys use underscores, not hyphens
3. Keys are case-sensitive

### Blog Post not found

```json theme={null}
{
  "detail": "Post matching query does not exist"
}
```

**Cause:** No blog post exists with the specified slug.

**Solution:**

1. Verify the post is published
2. Check the slug is correct
3. Ensure you're not including `/blog/` prefix in the slug

***

## Rate limit errors (429)

### Too Many Requests

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

**Cause:** A Free or Trial account exceeded its monthly API call limit and has been temporarily blocked.

**Solution:**

1. **Check usage:** Review API calls in your billing dashboard
2. **Reduce calls:** Cache responses and avoid polling
3. **Wait for reset:** The block lifts at the next billing cycle
4. **Upgrade if needed:** Paid plans are not blocked for monthly API overages

**Rate Limit Response Headers:**

| Header        | Description                                                         |
| ------------- | ------------------------------------------------------------------- |
| `Retry-After` | Seconds to wait before retrying (provided by API when rate limited) |

<Note>
  When you exceed your plan's monthly API call limit, the `Retry-After` value indicates the seconds remaining until the end of the current billing month when your limit resets.
</Note>

**Retry Logic Example:**

```javascript theme={null}
async function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url);
      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || 60;
        console.log(`API limit reached. Retrying in ${retryAfter}s...`);
        await new Promise(r => setTimeout(r, retryAfter * 1000));
        continue;
      }
      return response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
    }
  }
}
```

***

## Validation Errors

### Content validation failed

```json theme={null}
{
  "detail": {
    "fields": {
      "title": ["This field is required."],
      "slug": ["A page with this slug already exists."]
    }
  }
}
```

**Cause:** Content being created/updated fails validation rules.

**Solution:** Check each field mentioned in the error:

* Ensure required fields are provided
* Verify slugs are unique
* Check field values meet validation rules (min/max length, format)

### Schema Mismatch

```json theme={null}
{
  "detail": "Field 'hero_image' is not defined in this page type"
}
```

**Cause:** Trying to set a field that doesn't exist in the content schema.

**Solution:**

1. Check the page type schema in Content Types
2. Ensure field names match exactly
3. Update your code to match the current schema

***

## Server errors (500)

### Internal Server Error

```json theme={null}
{
  "detail": "An unexpected error occurred. Please try again later."
}
```

**Cause:** An unexpected error on ButterCMS servers.

**Solution:**

1. Wait a few minutes and retry
2. Check the [API Status Page](https://status.buttercms.com)
3. If persistent, [contact support](../contact-status/contact-support) with:
   * The exact endpoint you're calling
   * Request parameters
   * Timestamp of the error

***

## Error handling best practices

### JavaScript/TypeScript

```javascript theme={null}
async function safeFetch(fetchFn) {
  try {
    const response = await fetchFn();
    return { data: response.data, error: null };
  } catch (error) {
    const status = error.response?.status;
    const detail = error.response?.data?.detail;

    console.error(`ButterCMS Error [${status}]:`, detail);

    // Handle specific errors
    switch (status) {
      case 401:
        return { data: null, error: 'Authentication failed. Check your API token.' };
      case 404:
        return { data: null, error: 'Content not found.' };
      case 429:
        return { data: null, error: 'API limit reached. Please wait for the monthly reset.' };
      default:
        return { data: null, error: detail || 'An unexpected error occurred.' };
    }
  }
}
```

### Python

```python theme={null}
from butter_cms import ButterCMS
from butter_cms.exceptions import ButterCMSError

client = ButterCMS('your-api-token')

try:
    page = client.pages.get('landing_page', 'homepage')
except ButterCMSError as e:
    if e.status_code == 401:
        print("Authentication failed. Check your API token.")
    elif e.status_code == 404:
        print("Page not found.")
    elif e.status_code == 429:
        print("API limit reached. Please wait for the monthly reset.")
    else:
        print(f"Error {e.status_code}: {e.message}")
```

***

## Quick reference table

| Error Code | Common Cause          | Quick Fix                                         |
| ---------- | --------------------- | ------------------------------------------------- |
| 401        | Missing/invalid token | Check Settings > API Tokens                       |
| 400        | Invalid parameters    | Verify parameter values                           |
| 403        | Wrong page type       | Specify exact page type                           |
| 404        | Content not published | Publish the content                               |
| 429        | Too many requests     | Check usage, reduce calls, wait for monthly reset |
| 500        | Server issue          | Wait and retry, check status                      |

***

## Related resources

<CardGroup cols={2}>
  <Card title="Common Errors" icon="wrench" href="./common-errors-solutions">
    Step-by-step solutions for common issues
  </Card>

  <Card title="Debugging Guide" icon="bug" href="./debugging-guide">
    How to debug your integration
  </Card>

  <Card title="API Reference" icon="code" href="../../api/overview">
    Full API documentation
  </Card>

  <Card title="Contact Support" icon="headset" href="../contact-status/contact-support">
    Get help from our team
  </Card>
</CardGroup>
