# Fix API Request Failed Errors

Your application shows "API request failed" or similar errors when making HTTP requests. The error message is vague, and you need to diagnose the root cause - whether it's network, authentication, server, or client-side issues.

Introduction

"API request failed" is a generic error that can mean: - Network connectivity issues - DNS resolution failures - SSL/TLS certificate problems - Authentication failures - Server errors (5xx) - Client errors (4xx) - Timeout issues - Rate limiting

Symptoms

  • HTTP errors returned to clients
  • Connection timeout errors
  • Authentication failures
  • SSL certificate errors
  • Rate limit exceeded messages

Common error patterns:

bash
Error: API request failed
Error: connect ETIMEDOUT
Error: getaddrinfo ENOTFOUND
Error: certificate has expired
Error: 401 Unauthorized
Error: 429 Too Many Requests

Common Causes

  • Network connectivity blocked
  • DNS resolution failure
  • SSL/TLS certificate issues
  • Invalid or expired credentials
  • Server overload or downtime
  • Rate limiting triggered

Step-by-Step Fix

Test basic connectivity:

```bash # Test DNS resolution nslookup api.example.com dig api.example.com

# Test basic connectivity ping api.example.com

# Test HTTP connectivity curl -I https://api.example.com

# Test with verbose output curl -v https://api.example.com/api/v1/endpoint ```

Test specific endpoint:

```bash # GET request curl -X GET "https://api.example.com/api/v1/users" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -v

# POST request curl -X POST "https://api.example.com/api/v1/users" \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "John", "email": "john@example.com"}' \ -v ```

Check SSL certificate:

```bash # Check certificate openssl s_client -connect api.example.com:443 -servername api.example.com

# Check certificate expiration echo | openssl s_client -connect api.example.com:443 2>/dev/null | openssl x509 -noout -dates ```

Common Causes and Solutions

Cause 1: Network Connectivity Issues

bash
# Error: Connection refused, Network is unreachable

Diagnosis:

```bash # Check if host is reachable ping api.example.com

# Check if port is open nc -zv api.example.com 443

# Check routing traceroute api.example.com ```

Solution:

```python import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry

# Configure retry strategy retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], )

adapter = HTTPAdapter(max_retries=retry_strategy) session = requests.Session() session.mount("https://", adapter) session.mount("http://", adapter)

try: response = session.get( "https://api.example.com/endpoint", timeout=30 ) response.raise_for_status() except requests.exceptions.ConnectionError as e: print(f"Connection error: {e}") except requests.exceptions.Timeout as e: print(f"Timeout error: {e}") ```

Cause 2: DNS Resolution Failure

bash
# Error: Failed to resolve host

Diagnosis:

```bash # Check DNS nslookup api.example.com dig api.example.com

# Check /etc/resolv.conf cat /etc/resolv.conf ```

Solution:

```python import socket import requests

# Try to resolve DNS manually try: ip = socket.gethostbyname("api.example.com") print(f"Resolved to: {ip}") except socket.gaierror as e: print(f"DNS resolution failed: {e}")

# Use IP with Host header (if DNS is broken) response = requests.get( "https://1.2.3.4/endpoint", headers={"Host": "api.example.com"}, verify=False # SSL will fail without proper hostname ) ```

Cause 3: SSL/TLS Certificate Issues

bash
# Error: SSL certificate problem, certificate verify failed

Diagnosis:

```bash # Check certificate openssl s_client -connect api.example.com:443

# Check certificate chain curl -vI https://api.example.com 2>&1 | grep -A 10 "SSL certificate" ```

Solution:

```python import requests import certifi

# Use certifi's certificate bundle response = requests.get( "https://api.example.com/endpoint", verify=certifi.where() )

# Or specify custom CA bundle response = requests.get( "https://api.example.com/endpoint", verify="/path/to/ca-bundle.crt" )

# For development only - disable SSL verification (NOT for production) response = requests.get( "https://api.example.com/endpoint", verify=False ) ```

Cause 4: Authentication Failure

bash
# Error: 401 Unauthorized, 403 Forbidden

Diagnosis:

bash
# Test with curl
curl -v -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/endpoint

Solution:

```python import requests from requests.auth import HTTPBasicAuth

# Bearer token headers = { "Authorization": "Bearer YOUR_ACCESS_TOKEN", "Content-Type": "application/json" } response = requests.get("https://api.example.com/endpoint", headers=headers)

# Basic auth response = requests.get( "https://api.example.com/endpoint", auth=HTTPBasicAuth("username", "password") )

# API key headers = {"X-API-Key": "YOUR_API_KEY"} response = requests.get("https://api.example.com/endpoint", headers=headers)

# OAuth2 import requests_oauthlib

oauth = requests_oauthlib.OAuth2Session( client_id="CLIENT_ID", token={"access_token": "ACCESS_TOKEN", "token_type": "Bearer"} ) response = oauth.get("https://api.example.com/endpoint") ```

Cause 5: Timeout Issues

bash
# Error: Timeout, Request timed out

Solution:

```python import requests

# Set appropriate timeouts try: response = requests.get( "https://api.example.com/endpoint", timeout=(3.05, 30) # (connect timeout, read timeout) ) except requests.exceptions.Timeout: print("Request timed out")

# For long-running requests response = requests.get( "https://api.example.com/long-running-endpoint", timeout=300 # 5 minutes ) ```

Cause 6: Rate Limiting

bash
# Error: 429 Too Many Requests

Solution:

```python import requests import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry

# Handle rate limiting with retry def make_request(url, max_retries=3): session = requests.Session()

for attempt in range(max_retries): response = session.get(url)

if response.status_code == 429: retry_after = int(response.headers.get("Retry-After", 60)) print(f"Rate limited. Waiting {retry_after} seconds...") time.sleep(retry_after) continue

return response

raise Exception("Max retries exceeded")

# Or use exponential backoff def make_request_with_backoff(url, max_retries=5): for attempt in range(max_retries): try: response = requests.get(url) if response.status_code == 429: wait_time = 2 ** attempt time.sleep(wait_time) continue return response except requests.exceptions.RequestException: wait_time = 2 ** attempt time.sleep(wait_time)

raise Exception("Max retries exceeded") ```

Cause 7: Server Errors (5xx)

bash
# Error: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

Solution:

```python import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry

# Configure automatic retry for server errors retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504], allowed_methods=["GET", "POST", "PUT", "DELETE"] )

session = requests.Session() adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("https://", adapter)

try: response = session.get("https://api.example.com/endpoint") response.raise_for_status() except requests.exceptions.HTTPError as e: if e.response.status_code >= 500: print(f"Server error: {e}") # Implement fallback logic else: raise ```

Cause 8: Invalid Request Data

bash
# Error: 400 Bad Request

Solution:

```python import requests import json

# Validate request data data = {"name": "John", "email": "john@example.com"}

# Check JSON serialization try: json_data = json.dumps(data) except TypeError as e: print(f"Invalid data: {e}")

# Send request with proper headers response = requests.post( "https://api.example.com/users", json=data, # Automatically sets Content-Type: application/json headers={"Accept": "application/json"} )

# Check response for validation errors if response.status_code == 400: errors = response.json() print(f"Validation errors: {errors}") ```

Comprehensive Error Handling

```python import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry import logging

logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__)

class APIClient: def __init__(self, base_url, timeout=30): self.base_url = base_url self.timeout = timeout self.session = self._create_session()

def _create_session(self): retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["GET", "POST", "PUT", "DELETE"] )

session = requests.Session() adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("https://", adapter) session.mount("http://", adapter)

return session

def request(self, method, endpoint, **kwargs): url = f"{self.base_url}{endpoint}" kwargs.setdefault("timeout", self.timeout)

try: response = self.session.request(method, url, **kwargs) response.raise_for_status() return response.json()

except requests.exceptions.Timeout: logger.error(f"Request timed out: {url}") raise APITimeoutError("Request timed out")

except requests.exceptions.ConnectionError as e: logger.error(f"Connection error: {e}") raise APIConnectionError(f"Connection failed: {e}")

except requests.exceptions.HTTPError as e: status = e.response.status_code if status == 401: raise APIAuthenticationError("Authentication failed") elif status == 403: raise APIPermissionError("Permission denied") elif status == 404: raise APINotFoundError("Resource not found") elif status == 429: raise APIRateLimitError("Rate limit exceeded") elif status >= 500: raise APIServerError(f"Server error: {status}") else: raise APIError(f"HTTP error: {status}")

except requests.exceptions.RequestException as e: logger.error(f"Request failed: {e}") raise APIError(f"Request failed: {e}")

# Custom exceptions class APIError(Exception): pass

class APITimeoutError(APIError): pass

class APIConnectionError(APIError): pass

class APIAuthenticationError(APIError): pass

class APIRateLimitError(APIError): pass

class APIServerError(APIError): pass

# Usage client = APIClient("https://api.example.com")

try: data = client.get("/users/1") except APIAuthenticationError: # Refresh token and retry pass except APIRateLimitError: # Wait and retry pass except APIError as e: print(f"API error: {e}") ```

Verification

```bash # Test basic connectivity curl -I https://api.example.com

# Test with authentication curl -H "Authorization: Bearer TOKEN" https://api.example.com/endpoint

# Test with verbose output curl -v https://api.example.com/endpoint

# Check response time curl -w "Time: %{time_total}s\n" https://api.example.com/endpoint

# Check SSL openssl s_client -connect api.example.com:443 ```

Prevention

  1. 1.[ ] Check network connectivity (ping, nc)
  2. 2.[ ] Verify DNS resolution
  3. 3.[ ] Check SSL certificate validity
  4. 4.[ ] Verify authentication credentials
  5. 5.[ ] Check for rate limiting headers
  6. 6.[ ] Review server response codes
  7. 7.[ ] Implement proper timeout handling
  8. 8.[ ] Add retry logic for transient errors
  9. 9.[ ] Log request/response for debugging
  10. 10.[ ] Check API documentation for requirements
  11. 11.## Common Causes
  • Configuration misconfiguration
  • Missing or incorrect credentials
  • Network connectivity issues
  • Version compatibility problems
  • Resource exhaustion or limits
  • Permission or access denied

Related Articles

  • [AWS troubleshooting: Fix IAM Permission Denied - Complete Tro](fix-iam-permission-denied)
  • [AWS cloud troubleshooting: AWS ACM Certificate Pending Validation Because the](aws-acm-certificate-pending-validation-wrong-route53-zone)
  • [AWS cloud troubleshooting: AWS ALB Returns 502 Because the Target Closed the ](aws-alb-502-target-closed-connection-keepalive-timeout-mismatch)
  • [AWS cloud troubleshooting: Fix AWS ALB CreateListener TargetGroupNotFound Err](aws-alb-createlistener-targetgroupnotfound)
  • [AWS cloud troubleshooting: Fix Aws Alb Lambda 502 Bad Gateway Issue in AWS](aws-alb-lambda-502-bad-gateway)

<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix API Request Failed Errors", "description": "Step-by-step guide to fix API request failed errors. Diagnose network, authentication, and server issues. Implement proper error handling.", "url": "https://www.fixwikihub.com/fix-api-request-failed-errors", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-27T10:17:00.000Z", "dateModified": "2026-04-27T10:17:00.000Z" } </script>