API Navigator Logo

Setting a Timeout with Python Requests

Author: Newtum

Network requests can sometimes be slow or unresponsive. This guide explains how to set a timeout for your requests using the Python Requests library to prevent your application from hanging indefinitely.

Why Use a Timeout?

By default, requests will wait forever for a response. If the server is not responding, your program will be stuck. A timeout specifies a maximum time to wait for a response before raising an exception.

How to Set a Timeout

You can set a timeout in seconds with the `timeout` parameter. If the request takes longer than this, a `requests.exceptions.Timeout` exception is raised.

import requests

try:
    # This request will time out because the delay is longer than the timeout
    response = requests.get('https://httpbin.org/delay/5', timeout=3)
    print(response.status_code)
except requests.exceptions.Timeout:
    print('The request timed out.')

Connect vs. Read Timeout

You can also specify separate timeouts for connecting and reading. Pass a tuple to the `timeout` parameter: `(connect_timeout, read_timeout)`.

import requests

try:
    # (time to establish connection, time to wait for first byte)
    response = requests.get('https://httpbin.org/delay/5', timeout=(2, 6))
    print('Request was successful.')
except requests.exceptions.ConnectTimeout:
    print('The connection timed out.')
except requests.exceptions.ReadTimeout:
    print('The read timed out.')