Python request() Method:

The request() method of a requests module sends any specific request to a web server. In other words, we can use the request method to send any one of the get, post, put, patch, delete and head requests to a web server.

However, if required, this method can also handle custom HTTP verbs. This method has the same effect as calling a specific method.

Method Signature

The signature for the request method is as shown below.

requests.request(method, url, args)

Method parameters and return type

  • Here, the request method takes three parameters as listed below.
    • method – Any method name supported by the requests module is mandatory.
    • URL – Mandatory parameter. It specifies the URL
    • args – It can pass several arguments like cookies, headers, proxies, timeout, stream, auth and cert. These arguments are optional.
  • However, it returns a response object.

Python request method Examples:

Example 1: In this case, we will compare the output of get() method and the request method. Therefore, we will send requests to a URL and print the status code and reason for its response.

#Importing requests module
import requests

# variable storing url 
url="https://httpbin.org/get"

r1 = requests.get(url)
r2 = requests.request("GET", url)

print(r1.status_code)
print(r2.status_code)

Output

200
200

Example 2: In this case, we will request a method with POST method type and timeout argument. This method returns the response’s status if it arrives before the timeout. However, if not, it will raise the ReadTimeoutException.

#Importing requests module
import requests

# variable storing url 
url = "http://nhk.e6a.mytemp.website/python"

#Using the timeout parameter 
x = requests.request("POST",url, timeout=10)

print("Status code - ",x.status_code)

Output

Status code - 200

Example 3: In this case, we use the HEAD method and pass header parameters in a request method.

#Importing requests module
import requests

# variable storing url 
url = "https://httpbin.org/put"

#Using the headers parameter to set the HTTP headers:
h = {"HTTP_HOST": "onlinetut", "Content-Type":"application/json" }
x = requests.request("HEAD",url, headers = h)

print("Status code - ",x.status_code)
print("Reason - ",x.reason)

Output

Status code - 405
Reason - Method Not Allowed

Conclusion

Hence, the request() method can be alternatively used to perform various operations over the resource on a web server.

References

Happy Learning 🙂