API Error Codes: Explanations and Handling Strategies
Understand API error codes, master error-handling best practices, and build stable, reliable applications.
Quick identification
Accurately determine the error type
Graceful handling
User-friendly error messages
Smart retries
Automatic recovery mechanisms
Detailed logging
Issue tracking and analysis
1. Common Error Codes Cheat Sheet
400 - Bad Request
Malformed request or invalid parameters
Common causes:
- • Malformed JSON
- • Missing required parameters
- • Incorrect parameter types
- • Parameter values out of range
Solutions:
- ✓ Validate request body JSON format
- ✓ Verify all required parameters are present
- ✓ Ensure parameter types are correct
- ✓ Review API documentation for constraints
401 - Unauthorized
Authentication failed or invalid credentials
Common causes:
- • API key missing or incorrect
- • API key expired
- • Malformed Authorization header
- • API key not activated
Solutions:
- ✓ Check Authorization header
- ✓ Confirm API key is correct
- ✓ Regenerate API key
- ✓ Validate Bearer token format
403 - Forbidden
No permission to access the requested resource
Common causes:
- • Insufficient balance
- • Insufficient API key permissions
- • Accessing a restricted model
- • Account suspended
Solutions:
- ✓ Check account balance
- ✓ Verify API permission settings
- ✓ Upgrade to an appropriate plan
- ✓ Contact support for assistance
404 - Not Found
Requested resource not found
Common causes:
- • Incorrect API endpoint URL
- • Incorrect model name
- • Incorrect API version
- • Resource has been deleted
Solutions:
- ✓ Check request URL spelling
- ✓ Confirm model name
- ✓ Use the correct API version
- ✓ See the latest API documentation
429 - Too Many Requests
Request rate exceeds limits
Common causes:
- • Exceeded RPM limit
- • Exceeded TPM limit
- • Too many concurrent requests
- • Burst of requests in a short time
Solutions:
- ✓ Implement client-side throttling
- ✓ Use exponential backoff
- ✓ Batch requests
- ✓ Upgrade plan for higher limits
500 - Internal Server Error
Internal server error
Common causes:
- • Server processing exception
- • Internal service failure
- • Resource exhaustion
- • Unknown system error
Solutions:
- ✓ Retry the request later
- ✓ Record the error ID
- ✓ Contact technical support
- ✓ Check service status page
2. Unified Error Handling
Basic error handler
import requests
from typing import Optional, Dict
import json
import time
class APIErrorHandler:
"""Unified API error handler"""
def __init__(self):
self.error_handlers = {
400: self._handle_bad_request,
401: self._handle_unauthorized,
403: self._handle_forbidden,
404: self._handle_not_found,
429: self._handle_rate_limit,
500: self._handle_server_error,
503: self._handle_service_unavailable
}
def handle_api_call(self, func, *args, **kwargs) -> Optional[Dict]:
"""Wrap API calls with unified error handling"""
try:
response = func(*args, **kwargs)
# Check HTTP status code
if response.status_code == 200:
return response.json()
# Invoke corresponding error handler
handler = self.error_handlers.get(
response.status_code,
self._handle_unknown_error
)
return handler(response)
except requests.exceptions.ConnectionError:
print("❌ Connection error: Unable to connect to API server")
return None
except requests.exceptions.Timeout:
print("⏱️ Timeout: Request timed out, please retry later")
return None
except Exception as e:
print(f"🚨 Unknown error: {str(e)}")
return None
def _handle_bad_request(self, response):
"""Handle 400 - Bad request (invalid parameters)"""
error_data = response.json()
error_msg = error_data.get('error', {}).get('message', 'Bad request: invalid parameters')
print(f"❌ 400 Error: {error_msg}")
# Parse specific error hints
if "model" in error_msg:
print(" 💡 Tip: Check whether the model name is correct")
elif "max_tokens" in error_msg:
print(" 💡 Tip: max_tokens parameter exceeds limit")
elif "messages" in error_msg:
print(" 💡 Tip: Message format error, check role and content")
return None
def _handle_unauthorized(self, response):
"""Handle 401 - Authentication failed"""
print("🔐 401 Error: API key is invalid or expired")
print(" 💡 Tips:")
print(" 1. Verify the API key value")
print(" 2. Ensure the API key is activated")
print(" 3. Check that the Authorization header is correct")
return None
def _handle_forbidden(self, response):
"""Handle 403 - Insufficient permissions"""
error_data = response.json()
error_code = error_data.get('error', {}).get('code', '')
if error_code == 'insufficient_quota':
print("💳 403 Error: Insufficient quota/balance")
print(" 💡 Tip: Top up your balance before continuing")
else:
print("🚫 403 Error: No permission to access this resource")
print(" 💡 Tip: Check the permissions associated with your API key")
return None
def _handle_not_found(self, response):
"""Handle 404 - Resource not found"""
print("🔍 404 Error: The requested resource does not exist")
print(" 💡 Tips:")
print(" 1. Verify the API endpoint URL")
print(" 2. Confirm the model name")
print(" 3. Validate the API version")
return None
def _handle_rate_limit(self, response):
"""Handle 429 - Rate limited"""
retry_after = response.headers.get('Retry-After', 60)
print(f"⏳ 429 Error: Rate limit triggered, wait {retry_after} seconds")
# Show rate-limit info
limit = response.headers.get('X-RateLimit-Limit')
remaining = response.headers.get('X-RateLimit-Remaining')
if limit:
print(f" 📊 Rate limit: limit {limit}/minute, remaining {remaining}")
return None
def _handle_server_error(self, response):
"""Handle 500 - Internal server error"""
print("💥 500 Error: Internal server error")
print(" 💡 Tips:")
print(" 1. Retry later")
print(" 2. If the issue persists, contact technical support")
# Log detailed error information for debugging
error_id = response.headers.get('X-Request-ID')
if error_id:
print(f" 🆔 Error ID: {error_id}")
return None
def _handle_service_unavailable(self, response):
"""Handle 503 - Service unavailable"""
print("🔧 503 Error: Service temporarily unavailable")
print(" 💡 Tips:")
print(" 1. The service may be under maintenance")
print(" 2. Retry after a few minutes")
# Check maintenance metadata
maintenance_info = response.headers.get('X-Maintenance-Until')
if maintenance_info:
print(f" ⏰ Estimated recovery time: {maintenance_info}")
return None
def _handle_unknown_error(self, response):
"""Handle unknown errors"""
print(f"❓ {response.status_code} Error: Unknown error type")
try:
error_data = response.json()
print(f" 📝 Error details: {json.dumps(error_data, indent=2)}")
except:
print(f" 📝 Response content: {response.text[:200]}...")
return None
# Usage example
handler = APIErrorHandler()
def make_api_request():
return requests.post(
"https://api.n1n.ai/v1/chat/completions",
headers={"Authorization": "Bearer your-key"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello"}]
}
)
result = handler.handle_api_call(make_api_request)