Python - Send HTTP PUT Request
Python - Send HTTP PUT Request
HTTP PUT request is used to create or update a resource in a specified server, same as that of HTTP POST, but PUT request being idempotent.
In Python Requests library, requests.put() method is used to send a PUT request to a server over HTTP. You can also send additional data in the PUT request using data
parameter.
Examples
1. Send HTTP PUT request to server
In this example, we shall send a HTTP PUT Request to the server at /
. We shall also send data in the PUT request.
Python Program
import requests
response = requests.put('/', data = {'key':'value'})
requests.put() returns a Response object. It contains all the data and properties like response content, headers, encoding, cookies, etc. Let us print out headers.
Python Program
import requests
response = requests.put('/',
data = {'key1':'value1', 'key2':'value2'})
print(response.headers)
Output
{'Date': 'Mon, 25 Mar 2019 14:00:23 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': '12140', 'Connection': 'keep-alive', 'Keep-Alive': 'timeout=30', 'Server': 'Apache/2', 'X-Powered-By': 'PHP/A.A.AA', 'Link': '</wp-json/>; rel="https://api.w.org/", </>; rel=shortlink', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Referrer-Policy': 'no-referrer-when-downgrade'}
About HTTP PUT Request
Following are some of the points that you should keep in mind when working iwth HTTP PUT Request.
- PUT requests are never cached
- PUT requests do not remain in the browser history
- PUT requests cannot be bookmarked
- PUT requests have no restrictions on data length
Difference between POST and PUT
PUT is idempotent while POST is not. What does that mean? It means that when you call PUT any number of times, the result will be same every time. This behavior is not guaranteed with POST request. There is a chance that POST could create the same resource multiple times when requested multiple times.
Summary
In this tutorial of Python Examples, we learned how to send a PUT request to a server.