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:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: