# Errors

This API uses conventional HTTP response codes to indicate the success or failure of API requests.

## HTTP Status Codes

In general:
- **Codes in the 2xx range** indicate success
- **Codes in the 4xx range** indicate an error that failed given the information provided (e.g., a required parameter was omitted, endpoint not found, etc.)
- **Codes in the 5xx range** indicate an error with our API (these are rare)

### Common Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 400 | Bad Request - Invalid parameters |
| 401 | Unauthorized - Invalid or missing API key |
| 403 | Forbidden - API key doesn't have permission |
| 404 | Not Found - Resource doesn't exist |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error |

## Rate Limit Errors

When the rate limit is exceeded, an error is returned with the status "429 Too Many Requests", using the same `detail` envelope as every other error:

```json
{
  "detail": "Too many requests"
}
```

Check the response headers for rate limit information:
- `x-ratelimit-requests-limit` - Maximum requests allowed
- `x-ratelimit-requests-remaining` - Requests remaining in current window

## Error Response Format

Errors are returned in a consistent JSON format: a single `detail` key holding a human-readable message.

```json
{
  "detail": "Human-readable error message"
}
```

Examples of real responses:

| Status | Body |
|--------|------|
| 401 | `{"detail": "API key missing"}` |
| 401 | `{"detail": "Invalid API key"}` |
| 404 | `{"detail": "Not Found"}` |

## Error Handling

Always check the response status and handle errors appropriately:

```javascript
try {
  const response = await fetch(url, {
    headers: {
      'X-Api-Key': 'YOUR_API_KEY'
    }
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail);
  }
  
  const data = await response.json();
  // Handle successful response
} catch (error) {
  console.error('API Error:', error.message);
}
```

```python
import requests

try:
    response = requests.get(
        'https://api.serply.io/v1/search/q=query',
        headers={'X-Api-Key': 'YOUR_API_KEY'}
    )
    response.raise_for_status()
    data = response.json()
    # Handle successful response
except requests.exceptions.HTTPError as e:
    error = e.response.json()
    print(f"API Error: {error.get('detail', e)}")
```
