Occasionally when making HTTP requests in Python you may encounter a requests.exceptions.ConnectionError. This error indicates there was a network connectivity issue talking to the server. Here are some things to try to resolve it.
Check Internet Connectivity
First, ensure your computer or device actually has an internet connection. Try opening a website in your browser or pinging a domain like google.com:
ping google.com
If you cannot reach sites, resolve the network issue first before troubleshooting Python code.
Retry the Request
Intermittent network issues can cause a one-off ConnectionError. Retry sending the HTTP request in your code to see if it succeeds on a second attempt:
import requests
try:
response = requests.get('https://api.example.com/data')
except requests.exceptions.ConnectionError:
response = requests.get('https://api.example.com/data')
Adding a retry can help overcome temporary network blips.
Check the URL
Double check that the URL you are sending the request to is correct. A wrong or non-existent domain will fail to resolve and throw this error.
Print out the URL before sending the request to ensure it matches what the API endpoint should be.
Use a Timeout
You can set a timeout value in the request to avoid hanging if a server cannot be reached:
requests.get('https://api.example.com/data', timeout=3)
This will fail fast after 3 seconds rather than potentially waiting a long time. Tune the timeout as appropriate.
Following these troubleshooting tips should help resolve most occurrences of ConnectionError in Python requests. Ensure connectivity, retry failed requests, check URLs carefully, and use timeouts to prevent long delays.