🔧 Error Fixes
· 1 min read

Python ConnectionError / requests.exceptions.ConnectionError — How to Fix It


requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded

Python can’t connect to the server. The server is down, unreachable, or your network is blocking the connection.

Fix 1: Check if the URL is correct

# ❌ Typo in URL
response = requests.get("https://api.exmple.com/data")

# ✅ Correct URL
response = requests.get("https://api.example.com/data")

Fix 2: Check your internet connection

ping api.example.com
curl https://api.example.com

Fix 3: Add retry logic

import requests
from requests.adapters import HTTPAdapter, Retry

session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503])
session.mount("https://", HTTPAdapter(max_retries=retries))

response = session.get("https://api.example.com/data")

Fix 4: Add a timeout

# ❌ No timeout — hangs forever if server doesn't respond
response = requests.get("https://api.example.com/data")

# ✅ Set a timeout (seconds)
response = requests.get("https://api.example.com/data", timeout=10)

Fix 5: Handle the error gracefully

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()
except requests.exceptions.ConnectionError:
    print("Could not connect to server")
except requests.exceptions.Timeout:
    print("Request timed out")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e}")
📘