First, ensure that the requests library is installed. If not installed, you can install it by running the following command:
bashpip install requests
After installation, you can use the following code to perform an HTTP PUT request:
pythonimport requests url = 'http://example.com/api/resource' data = { 'key1': 'value1', 'key2': 'value2' } response = requests.put(url, json=data) print(response.status_code) print(response.json())
In this example, we first import the requests library, define the request URL and data payload, and then use the requests.put method to send the PUT request with the data formatted as JSON. After executing the request, we print the response status code and parsed JSON content.
This approach is ideal for scenarios requiring modification or updates to server-side resources. For instance, when developing a web application that needs to update user information on the server, you can leverage the PUT request to accomplish this.
Additionally, while the http.client module in Python's standard library or third-party libraries like httpx can perform similar operations, the requests library is widely preferred due to its simplicity, readability, and ease of use.