Requests delete method:
The delete() method of requests module sends a request to delete data from a web server. The delete method takes additional parameters while communicating with the server. Thus, the response object contains several information like the web page text, status code, and the reason.
- The common code returned by the response object is as shown below :
- 405 – the method is not allowed
- 202 – the action is pending
- 200 – the action has been taken and the response message describes the status
- 204 – the action has been taken, but no further information is available
Method Signature
The signature for the delete()
method is as shown below.
requests.delete(url, params={key: value}, args)
Method parameters and return type
- Here, the delete method takes three parameters as listed below.
- url – Mandatory parameter. It specifies the URL
- params – It sends a dictionary, list of tuples, bytes to send as a query string. This is an optional parameter.
- 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 delete method Examples:
Example 1: In this case, we will send requests to a URL and print the status code and reason of its response.
#Importing requests module
import requests
# variable storing url
url="http://nhk.e6a.mytemp.website/python"
# Making a delete request
r = requests.delete(url)
# Checking status code and reason of response
# success code - 200
print("Status code - ",r.status_code)
print("Reason - ",r.reason)
Output
Status code - 405
Reason - Method Not Allowed
Example 2: In this case,we will use the header parameter to set the HTTP headers on the given URL. Here, we will use the URL page that does not exist. Hence, it will return the code for page not found.
#Importing requests module
import requests
# variable storing url
url = "http://nhk.e6a.mytemp.website/perl"
#Using the headers parameter to set the HTTP headers:
h = {"HTTP_HOST": "onlinetut", "Content-Type": "application/json" }
x = requests.delete(url, headers = h)
print("Status code - ",x.status_code)
print("Reason - ",x.reason)
Output
Status code - 404
Reason - Not Found
Example 3: In this case, this method returns the response’s status if it arrives before 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.delete(url, timeout=10)
print("Status code - ",x.status_code)
print("Reason - ",x.reason)
Output
Status code - 405
Reason - Method Not Allowed
Conclusion
Hence, the delete() method removes the data of the specified URL from the server.
References
Happy Learning 🙂