How to Use Timeout with Python Requests (With Examples)
PythonLearn how to effectively manage timeouts in Python Requests. Discover best practices and solutions to enhance your API interactions.

Vilius Dumcius
Key Takeaways
-
Use the timeout parameter in every HTTP request to avoid hanging and detect slow responses early.
-
Catch timeout exceptions with try/except blocks to safely handle exceptions without crashing your app.
-
Adjust timeout values and use retry logic based on your use case.
The Python Requests library is a simple and powerful tool you can use to send HTTP requests in Python. It makes it easy to fetch data from web servers and interact with APIs. However, when you send HTTP requests, the server may not be able to respond instantly, and that’s where the timeout parameter comes in handy.
Timeouts help your code avoid hanging forever. They define how long your program should wait before giving up on a low or unresponsive server. Without proper request timeouts, your app can freeze, crash, or start behaving erratically.
What Is the Timeout Parameter in Python Requests?
The timeout parameter is a setting that controls how long your code will wait for a response after sending an HTTP request using the Python Requests library.
First of all, make sure you install Requests before using it:
pip install requests
When you use the Requests library, you can pass timeout to set a maximum wait time. There are two essential parts to this:
- connect timeout. How long to wait to establish a connection.
- read timeout. How long to wait to read the response after connecting.
It works like this:
import requests
response = requests.get('https://iproyal.com', timeout=5)
Based on the example above, if the server doesn’t respond in 5 seconds, the Python Requests call will raise a timeout exception. It means your program can catch the delay and decide what to do next.
You can also split the timeout parameter into two values:
import requests
response = requests.get('https://iproyal.com', timeout=(3, 7)) # (connect timeout, read timeout)
Using (3, 7) means the code will wait up to 3 seconds to connect (raises ConnectTimeout error otherwise) and up to 7 seconds for a response (otherwise, raises a ReadTimeout error).
Handling Timeout Exceptions
When a server is slow or down, Python Requests might raise an exception. You can catch it using a try/except block. It lets you retry, show an error message, or use fallback logic.
Try/Except Example
import requests
url = "https://iproyal.com/api"
try:
response = requests.get(url, timeout=4)
print("Success:", response.status_code)
except requests.exceptions.Timeout:
print("Timeout! Trying again later.")
Such a pattern helps you handle timeouts cleanly. If the server doesn’t reply in time, your app won’t crash. You can also retry with backoff or notify the user.
When you’re handling timeouts, think about what matters most and whether retrying is worth it in the first place. Decide if the user should see a message. In some cases, fallback logic or cached data can help.
It’s also helpful to handle timeout exceptions when scraping or calling third-party APIs. One bad server shouldn’t break your whole app.
How to Use Timeout in GET and POST Requests
You can add the timeout parameter to any request method, like GET or POST . It tells the Python Requests library how long to wait before timing out.
GET Request With Timeout
import requests
try:
response = requests.get('https://httpbin.org/delay/10', timeout=5)
print(response.text)
except requests.exceptions.Timeout:
print("Request timed out.")
In this case, the server delays the response by 10 seconds, but we’ve also set a timeout of 5. So, the code prints a message when the exception is triggered.
POST Request With Timeout
import requests
try:
response = requests.post('https://httpbin.org/post', data={'key': 'value'}, timeout=(2, 4))
print(response.json())
except requests.exceptions.Timeout:
print("POST request timed out.")
Here, (2, 4) sets the connect timeout to 2 seconds, and the ReadTimeout error will occur if it waits for more than 4 seconds after connecting.
When a timeout happens, you’ll get a timeout exception. Not a status code like 500 or 404. Mainly because no full response was ever received.
Best Practices for Using Timeouts
To have the best experience while using timeouts, follow these practices:
- APIs. Use timeout values of 3-10 seconds. Too short might break during natural network delays.
- Web scraping. 5-15 seconds is generally acceptable. Some sites can be slow to load.
- Automation scripts. Set short connection timeouts like 2-4 seconds and longer *ReadTimeout *error values up to 10 seconds.
Short vs Long Timeouts
Short timeouts make your app faster and more responsive. But they might trigger more timeout exceptions on slower networks. Long timeouts reduce errors but delay the detection of failed requests.
In general, it’s all about finding your balance. If you set limits that are too short, you’ll likely miss out on valuable responses. If they’re too long, your app might feel stuck. You need to match timeout values to your use case.
Retry Logic
Combining timeouts with retry logic helps improve stability. You can retry a few times before giving up:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('https://', adapter)
try:
response = session.get('https://iproyal.com', timeout=(2, 6))
except requests.exceptions.Timeout:
print("Timeout even after retries.")
Here, retries will happen on connection timeouts. The setup above avoids giving up too quickly while still protecting your app from long delays.