Last modified: Nov 12, 2024 By Alexander Williams

Python requests.PUT(): Complete Guide for HTTP PUT Requests

The requests.put() method in Python allows you to send HTTP PUT requests to update existing resources on a server. Similar to POST requests, but specifically for updating data.

Understanding PUT Requests

PUT requests are used to modify existing resources where the client sends the complete updated version. Unlike GET requests, PUT requests can include a request body.

Basic PUT Request Syntax


import requests

url = "https://api.example.com/items/1"
data = {"name": "Updated Item", "description": "New description"}

response = requests.put(url, json=data)
print(response.status_code)
print(response.json())

Adding Headers to PUT Requests

You can include headers in your PUT requests to provide additional information. Here's how to add headers to your requests:


headers = {
    "Authorization": "Bearer your-token",
    "Content-Type": "application/json"
}

response = requests.put(url, json=data, headers=headers)

Handling PUT Response

Always check the response status code to ensure your PUT request was successful. Status code 200 or 204 typically indicates success.


response = requests.put(url, json=data)
if response.status_code == 200:
    print("Resource updated successfully")
    print(response.json())
else:
    print(f"Error: {response.status_code}")

Using PUT with Files

You can also use PUT requests to update files on a server:


with open('updated_file.txt', 'rb') as file:
    response = requests.put(url, files={'file': file})

Using PUT with Proxy

If you need to use a proxy, you can configure it with your PUT request:


proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

response = requests.put(url, json=data, proxies=proxies)

Complete PUT Request Example


import requests

def update_resource():
    url = "https://api.example.com/items/1"
    data = {
        "name": "Updated Item",
        "description": "New description"
    }
    headers = {
        "Authorization": "Bearer your-token",
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.put(url, json=data, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error occurred: {e}")
        return None

result = update_resource()
if result:
    print("Update successful:", result)

Handling Errors

It's important to handle potential errors when making PUT requests. Here's an example with proper error handling:


try:
    response = requests.put(url, json=data)
    response.raise_for_status()
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
    print(f"Error connecting: {conn_err}")
except Exception as err:
    print(f"Other error occurred: {err}")

Conclusion

The requests.put() method is a powerful tool for updating resources via HTTP. Remember to always handle responses and errors appropriately, and include necessary headers and authentication when required.

Make sure you have the requests library installed properly. If you encounter any issues, check out how to solve common requests module problems.