How do I set a timeout in Python Requests?

To set a timeout in Python Requests, you can pass the "timeout" parameter for GET, POST, PUT, HEAD, and DELETE methods. The "timeout" parameter allows you to select the maximum time (number of seconds) for the request to complete. By default, requests do not have a timeout unless you explicitly specify one. It is recommended to set a timeout for nearly all requests; otherwise, your code may freeze, and your program will become non-responsive. If the remote server is slow, or you want to wait for the request to complete, you can tell the request library to wait forever by passing "None" as the value for the timeout parameter. In this Python Example, we pass a timeout parameter in the GET request to indicate how long to wait for a server response. Click Execute to run Python Timeout Example online and see the result.
How do I set a timeout in Python Requests? Execute
import requests

r = requests.get('https://reqbin.com/echo', timeout=5)

print(f"Status Code: {r.status_code}")
Updated: Viewed: 6041 times

What is the Python Request Library?

Requests Library is a prevalent Library that makes it easy to send HTTP requests using POST, GET and DELETE methods. The Requests Library is based on the urllib3 library and conceals the complexity of making HTTP requests behind a simple API. The Requests Library automatically validates the server's SSL certificates and supports International Domain Names and session cookies. The Requests Library is not included in the Python distribution, but everyone uses it because the Python code for HTTP becomes short, simple, and straightforward.

How to install the Python Requests Library?

You can install the Requests Library using the pip package installer for Python:

Install Python Requests Library
pip install requests

After installing the Requests Library, you can use it in your code by importing the Requests Library with the following Python code:

Import Requests Syntax
import requests

See also