Python Requests put method:
The put() method of requests module sends a put request to a web server. The put() requests are idempotent, which means multiple requests will have the same result. In other words, the put() method is same as the post() method but multiple put requests overwrite the same resource whereas multiple post requests create new resource each time.
Thus, put()
performs update operations while post()
performs create operations.
The common code returned by 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 put method is as shown below.
requests.put(url, data, args)
Method parameters and return type
- Here, the put method takes three parameters as listed below.
- url – Mandatory parameter. It specifies the URL
- data – 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 put 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="https://google.com"
# Making a put request
r = requests.put(url)
# Checking status code and reason of response
print("Status code for Google- ",r.status_code)
print("Reason for Google - ",r.reason)
Output
Status code for Google - 405
Reason for Google - Method Not Allowed
Example 2: In this case, we will send json to the request body in order to create or update a resource on the given URL.
#Importing requests module
import requests
# variable storing url and json
url = "https://httpbin.org/put"
j = {"k1":"Python Programming"}
#Using the headers parameter to set the HTTP headers:
x = requests.put(url, json=j)
print("Status code - ",x.status_code)
print(x.json()['json']['k1'])
Output
Status code - 200
Python Programming
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.put(url, timeout=10)
print("Status code - ",x.status_code)
print("Reason - ",x.reason)
Output
Status code - 405
Reason - Method Not Allowed
Conclusion
Hence, the put() method performs the update or create operations for the resource on the server.
References
Happy Learning 🙂