Python Requests – HTTP PUT – Example

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.

Example 1: Send HTTP PUT Request

In this example, we shall send a HTTP PUT Request to the server at https://pythonexamples.org/. We shall also send data in the PUT request.

Python Program

import requests

response = requests.put('https://pythonexamples.org/', data = {'key':'value'})
Run this program

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('https://pythonexamples.org/',
            data = {'key1':'value1', 'key2':'value2'})
print(response.headers)
Run this program

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': '<https://pythonexamples.org/wp-json/>; rel="https://api.w.org/", <https://pythonexamples.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.