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

# ENS Ads API Error Handling: Status Codes 400, 401, 429

> Every ENS Ads error includes a status code and message field. Learn what each error means and see JavaScript and Python patterns for handling them gracefully.

Every error response from the ENS Ads API follows a consistent structure with two fields: `status`, which is always `"error"` for failed requests, and `message`, which describes what went wrong. Building your integration to check for these fields before attempting to use the response data will make your implementation resilient to transient failures, misconfiguration, and rate limits.

<Warning>
  Always check the response status before attempting to render campaigns or record tracking events. Rendering a failed or empty response as though it were valid data can result in broken UI states or inaccurate performance reporting.
</Warning>

## HTTP status code overview

| Status code | Name                  | Meaning                                     |
| ----------- | --------------------- | ------------------------------------------- |
| 200         | OK                    | Request succeeded. Use the response data.   |
| 400         | Bad Request           | A required parameter is missing or invalid. |
| 401         | Unauthorized          | Your API key is missing or incorrect.       |
| 404         | Not Found             | The requested resource does not exist.      |
| 429         | Too Many Requests     | You have exceeded the rate limit.           |
| 500         | Internal Server Error | A server-side error occurred. Retry later.  |

## Error responses

### 400 — missing required parameter

You will receive a 400 when a required query parameter is absent. The most common cause is omitting `placement` from a `GET /campaigns/fetch` request.

```json theme={null}
{
  "status": "error",
  "message": "placement parameter is required"
}
```

Check that all required parameters are present before making the request. For `GET /campaigns/fetch`, `placement` is the only required query parameter.

### 401 — unauthorized

A 401 means the API key in your `Authorization` header is missing, malformed, or does not match a valid key.

```json theme={null}
{
  "status": "error",
  "message": "unauthorized"
}
```

Confirm that your request includes the header `Authorization: Bearer YOUR_API_KEY` and that the key value is correct. API keys must never be included in client-side code.

### 404 — not found

A 404 is returned when the resource you are trying to reach does not exist. This can occur if a `campaignId` passed to the impression or click endpoints no longer corresponds to an active campaign.

### 429 — rate limit exceeded

A 429 means your integration is making requests faster than the API allows.

```json theme={null}
{
  "status": "error",
  "message": "Rate limit exceeded"
}
```

Implement exponential backoff when you receive a 429. Wait before retrying and reduce request frequency if you hit this error repeatedly.

### 500 — internal server error

A 500 indicates a server-side problem. These are typically transient. Log the error and retry the request after a short delay. If the problem persists, contact ENS Ads support.

## Error handling patterns

The examples below show how to catch and respond to API errors in both JavaScript and Python.

<CodeGroup>
  ```javascript error-handling.js theme={null}
  const BASE_URL = 'https://ads.enslive.live/api/v1';
  const API_KEY = 'YOUR_API_KEY';

  async function fetchCampaigns(placement, location, device) {
    try {
      const response = await fetch(
        `${BASE_URL}/campaigns/fetch?placement=${placement}&location=${location}&device=${device}`,
        {
          headers: {
            'Authorization': `Bearer ${API_KEY}`
          }
        }
      );

      if (!response.ok) {
        const error = await response.json();
        console.error(`API error ${response.status}:`, error.message);

        if (response.status === 401) {
          // Stop execution — API key problem requires manual fix
          throw new Error('Invalid API key. Check your Authorization header.');
        }

        if (response.status === 429) {
          // Back off and retry
          console.warn('Rate limit hit. Retrying after delay...');
        }

        return [];
      }

      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('Failed to fetch campaigns:', error);
      return [];
    }
  }
  ```

  ```python error_handling.py theme={null}
  import requests

  BASE_URL = 'https://ads.enslive.live/api/v1'
  API_KEY = 'YOUR_API_KEY'

  headers = {
      'Authorization': f'Bearer {API_KEY}',
      'Content-Type': 'application/json'
  }

  def fetch_campaigns(placement, location=None, device=None):
      """Fetch campaigns with error handling"""
      try:
          params = {'placement': placement}
          if location:
              params['location'] = location
          if device:
              params['device'] = device

          response = requests.get(
              f'{BASE_URL}/campaigns/fetch',
              params=params,
              headers=headers
          )

          if response.status_code == 401:
              # Stop execution — API key problem requires manual fix
              raise ValueError('Invalid API key. Check your Authorization header.')

          if response.status_code == 429:
              # Back off and retry
              print('Rate limit hit. Retrying after delay...')
              return []

          response.raise_for_status()
          return response.json()['data']

      except requests.exceptions.HTTPError as e:
          error_body = e.response.json() if e.response else {}
          print(f'API error {e.response.status_code}: {error_body.get("message", str(e))}')
          return []
      except requests.exceptions.RequestException as e:
          print(f'Request failed: {e}')
          return []
  ```
</CodeGroup>
