Making HTTP PUT Requests in Python

Feb 3, 2024 ยท 2 min read

The HTTP PUT method is used to update resources on a server. With PUT, you can upload content to a specified URI to create or update the resource.

In Python, you can easily make PUT requests using the requests library. Here's a quick example:

import requests

url = "http://example.com/api/users/1"
payload = {"name": "John Doe"}

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

This sends a PUT request to update the user with ID 1, setting their name to "John Doe".

Key Points for PUT Requests in Python

Here are some key things to note about making PUT requests in Python:

  • Use the requests.put() method, passing the URL and data
  • You can pass data as a dict using the json parameter
  • Check the status_code of the response to see if it succeeded
  • Authentication is easy - just use the auth parameter of requests.put()
  • Uploading Binary Data

    In addition to JSON, you can upload images, files, or other binary data with PUT:

    with open("image.jpg", 'rb') as f:
        image_data = f.read()
    
    response = requests.put(url, data=image_data) 

    This uploads the contents of the image file in binary format.

    Challenges

    Some challenges you may encounter:

  • Ensuring you have permission to PUT to the given URL
  • Handling errors and unsuccessful status codes
  • Setting the right content-type header for the data
  • But overall, Python and requests makes it very straightforward to do HTTP PUTs. The requests library handles all the nitty gritty details for you.

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!