Requests Timeout in Python

Requests Timeout in Python

We will introduce the timeout in Python’s requests method.

Requests Timeout in Python

The requests library is used to make HTTP requests in Python. It hides the complexity of requesting behind a beautiful and simple API so we can focus on interacting with services and consuming data in our application.

The requests have a built-in argument for a timeout that can be used to define the maximum timeout a request can have while making an HTTP request.

When we make an inline request to an external service or a website, our system will need to wait on the response from that external service before moving forward. If our application waits too long for the response, our user experience will suffer, resulting in hanging background jobs.

The requests can wait for unlimited time by default, but it provides us a feature to specify a timeout duration to prevent the application from waiting for too long. We can use the timeout for our request by using the timeout parameter.

We can use the timeout as an integer or a float representing the number of seconds our request will wait before timing out.

Let’s go through an example in which we will use timeout while making an HTTP request. Let’s begin by installing the requests library by running the following command.

# python
pip install requests

Once we have installed the requests library, import it.

# python
import requests

Using the timeout parameter, we will make an HTTP request to https://api.github.com.

# python
requests.get('https://api.github.com', timeout=5)

The above code shows that it will wait for 5 seconds before timing out. Now let’s pass a float instead of an integer.

# python
requests.get('https://api.github.com', timeout=5.5)

Our request will wait for 5.5 seconds before timing out. We can pass a tuple if we want to have different timeouts for connection and reading.

We will pass two values of timeouts in the timeout parameter. The first one will be for the connection timeout, and the second will be for the read timeout.

Let’s use it as an example.

# python
requests.get('https://api.github.com', timeout=(5, 7))

The above example shows that our request will allow 5 seconds for the client to establish a connection to the server, and it will allow 7 seconds to wait for the response once the connection has been established between the client and the server.

So in this way, we can use a timeout in our requests method to wait for the response or set it up for both connection wait and response wait by passing a tuple.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Python Request

  • Implement Timeout in Python Requests