Error Responses
When an error occurs, the API returns a consistent error response format along with appropriate HTTP status codes. All error responses follow the same structure to make error handling predictable.
Error Response Format
Section titled “Error Response Format”All errors return a consistent JSON object with both an error field (containing the error category) and a message field (containing specific details about what went wrong).
Standard Error Response
Section titled “Standard Error Response”{ "error": "Error Category", "message": "Detailed description of what went wrong"}Example: Validation Error
Section titled “Example: Validation Error”{ "error": "Bad Request", "message": "Invalid start_date format. Use YYYY-MM-DD."}HTTP Status Codes
Section titled “HTTP Status Codes”400 - Bad Request
Section titled “400 - Bad Request”Your request contains invalid parameters or malformed data. Common causes include invalid date formats, incorrect ISO codes, out-of-range values, or missing required parameters. Check the error message for specific validation details.
Example:
{ "error": "Bad Request", "message": "Invalid start_date format. Use YYYY-MM-DD."}401 - Unauthorized
Section titled “401 - Unauthorized”Your API key is missing, invalid, expired, or deactivated. Verify that you’re including the X-API-Key header with a valid, active key from your dashboard.
Example:
{ "error": "Unauthorized", "message": "API key is either invalid or expired/deactivated."}403 - Forbidden
Section titled “403 - Forbidden”Access denied due to insufficient permissions or quota exhaustion. This can occur if:
- You’ve exhausted your monthly/daily quota: Visit https://newsdatahub.com/plans to upgrade your plan or wait for your quota to reset (check
X-Quota-Resetheader for reset time) - Your plan doesn’t include access to the requested endpoint
- You’re attempting to access restricted resources
- Your API key permissions are limited
If you recently created a new key, allow a few minutes for changes to propagate. For persistent issues, contact support at support@newsdatahub.com.
Example (Quota Exhausted):
{ "error": "Quota Exceeded", "message": "You have exhausted your monthly/daily API quota. Visit https://newsdatahub.com/plans to upgrade your plan or wait for your quota to reset."}Example (Access Denied):
{ "error": "Access Forbidden", "message": "You don't have permission to access this resource. Check your subscription plan or API key permissions."}404 - Not Found
Section titled “404 - Not Found”The requested endpoint or resource doesn’t exist. This can happen if you’re using an incorrect URL, referencing a non-existent article ID, or accessing a deprecated endpoint. Verify your endpoint path and resource identifiers.
Example:
{ "error": "Not Found", "message": "The requested endpoint or resource was not found. Please check your URL and try again."}429 - Too Many Requests
Section titled “429 - Too Many Requests”You’re making requests too quickly and have exceeded the per-minute rate limit for your tier. This is a temporary throttling mechanism - slow down your request frequency and try again.
What to do:
- Implement exponential backoff retry logic
- Add delays between requests
- Check
X-RateLimit-*headers for your current limits - Consider caching responses to reduce request volume
Note: This is different from quota exhaustion (403). Rate limits are per-minute restrictions, while quotas (403) are daily/monthly allocations.
Example:
{ "error": "Rate Limit Exceeded", "message": "You are making requests too quickly. Please slow down and try again. Check the X-RateLimit-* headers for your current limits."}500 - Service Unavailable
Section titled “500 - Service Unavailable”An unexpected server error occurred. These are temporary issues on our end. Implement retry logic with exponential backoff. If the error persists, contact support at support@newsdatahub.com.
Example:
{ "error": "Service Unavailable", "message": "Unable to search articles at this time. Please try again later. If error persists contact support at support@newsdatahub.com"}Error Handling Best Practices
Section titled “Error Handling Best Practices”-
Check HTTP Status Codes First: The status code tells you the error category (client error vs server error) and determines whether to retry the request.
-
Parse Error Messages for Details: The
messagefield provides specific, actionable information about what went wrong. Display these to users or log them for debugging. -
Monitor Quota Headers: Always check
X-Quota-Remaining,X-Quota-Limit,X-Quota-Used,X-Quota-Reset, andX-Quota-Typeto track usage and prevent hitting limits. -
Implement Smart Retry Logic: Retry 5xx errors with exponential backoff (2^attempt seconds). Retry 429 (rate limit) errors after a brief delay. Never retry 4xx errors (except 429) as they indicate client-side issues. Never retry 403 quota errors - upgrade plan or wait for reset. Set a maximum retry limit (typically 3 attempts).
-
Validate Parameters Client-Side: Check date formats, ISO codes, and parameter ranges before making requests to reduce 400 errors and improve user experience.
-
Cache Responses: Store API responses when possible to reduce request volume, lower costs, and improve application performance.
-
Handle Network Errors: Implement timeout handling and catch network-level errors separately from HTTP errors for robust error recovery.
Error Handling Code Examples
Section titled “Error Handling Code Examples”try { const response = await fetch('https://api.newsdatahub.com/v1/news', { headers: { 'X-API-Key': 'your-api-key', 'User-Agent': 'docs-error-responses/1.0-js' } });
if (!response.ok) { const error = await response.json(); const errorMsg = error.message || error.error;
switch (response.status) { case 400: console.error('Bad request:', errorMsg); break; case 401: console.error('Invalid API key:', errorMsg); break; case 403: if (error.error === 'Quota Exceeded') { console.error('Quota exhausted:', errorMsg); const quotaReset = response.headers.get('X-Quota-Reset'); console.log('Quota resets at:', new Date(quotaReset * 1000)); console.log('Upgrade at: https://newsdatahub.com/plans'); } else { console.error('Access denied:', errorMsg); } break; case 429: console.error('Rate limited - too many requests:', errorMsg); // Implement exponential backoff and retry break; case 500: console.error('Server error:', errorMsg); // Implement retry logic with exponential backoff break; default: console.error('Unexpected error:', errorMsg); } return; }
const data = await response.json(); // Handle successful response} catch (error) { console.error('Network error:', error);}import requestsimport time
def make_api_request(url, headers, max_retries=3): for attempt in range(max_retries): try: response = requests.get(url, headers=headers)
if response.status_code == 200: return response.json()
error_data = response.json() error_msg = error_data.get('message', error_data.get('error'))
if response.status_code == 400: print(f'Bad request: {error_msg}') return None # Don't retry validation errors elif response.status_code == 401: print(f'Invalid API key: {error_msg}') return None # Don't retry auth errors elif response.status_code == 403: error_data = response.json() if error_data.get('error') == 'Quota Exceeded': print(f'Quota exhausted: {error_msg}') quota_reset = response.headers.get('X-Quota-Reset') if quota_reset: reset_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(quota_reset))) print(f'Quota resets at: {reset_time}') print('Upgrade at: https://newsdatahub.com/plans') else: print(f'Access denied: {error_msg}') return None # Don't retry permission/quota errors elif response.status_code == 429: print(f'Rate limited - too many requests: {error_msg}') # Implement exponential backoff retry if attempt < max_retries - 1: wait_time = 2 ** attempt print(f'Retrying in {wait_time} seconds...') time.sleep(wait_time) continue return None elif response.status_code >= 500: print(f'Server error: {error_msg}') if attempt < max_retries - 1: wait_time = 2 ** attempt # Exponential backoff print(f'Retrying in {wait_time} seconds...') time.sleep(wait_time) continue else: print(f'Unexpected error: {error_msg}') return None
except requests.exceptions.RequestException as e: print(f'Network error: {e}') if attempt < max_retries - 1: wait_time = 2 ** attempt print(f'Retrying in {wait_time} seconds...') time.sleep(wait_time) continue
return None
# Usageurl = 'https://api.newsdatahub.com/v1/news'headers = { 'X-API-Key': 'your-api-key', 'User-Agent': 'docs-error-responses/1.0-py'}data = make_api_request(url, headers)Need Help?
Section titled “Need Help?”If you encounter persistent errors or need assistance with error handling:
- Review the Authentication guide for API key issues
- Check Quota Headers for rate limit details
- Check our Learning Center for tutorials and guides
- Contact support@newsdatahub.com for technical support