Troubleshooting requests.exceptions.ConnectionError in Python

Feb 3, 2024 ยท 2 min read

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.

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: