How to send PUT requests using requests.put in Python

How to send PUT requests using requests.put in Python

Install requests into the same Python environment that will run your script:

python -m pip install requests

Before sending a PUT, inspect the endpoint’s current behavior. Use the API’s documented URL and a resource you’re authorized to access; the example below uses a placeholder URL.

import requests

url = "https://api.example.com/items/42"

response = requests.get(url, timeout=10)
print("status:", response.status_code)
print("content type:", response.headers.get("Content-Type"))
print("body:", response.text)

A successful GET does not guarantee that PUT is supported. Check the endpoint documentation for its accepted payload and authentication requirements; if the server advertises allowed methods, the Allow response header can provide another clue.

Build a PUT request with headers and a payload

For a JSON API, pass the resource fields as a Python dictionary through json=. Requests serializes it and sets Content-Type: application/json; set headers explicitly when the API requires additional metadata or a particular content type.

import requests

url = "https://api.example.com/items/42"
payload = {
    "name": "updated item",
    "enabled": True,
}
headers = {
    "Accept": "application/json",
    "Authorization": "Bearer YOUR_TOKEN",
}

request = requests.Request(
    "PUT",
    url,
    json=payload,
    headers=headers,
)
prepared = request.prepare()

print(prepared.method)
print(prepared.url)
print(prepared.headers)
print(prepared.body)

Preparing the request lets you inspect the method, URL, headers, and serialized body without contacting the server. Keep credentials out of source control; load tokens from the environment or another secret store. If the endpoint expects form data rather than JSON, use data= with the documented fields instead.

Send the request and inspect the response

Once the prepared request looks right, send it with a finite timeout. A timeout bounds how long the client waits; it does not prove that the server failed to apply the change, since the request may have reached the server before the connection stalled.

with requests.Session() as session:
    response = session.send(prepared, timeout=10)

print("status:", response.status_code)
print("content type:", response.headers.get("Content-Type"))
print("body:", response.text)

Many APIs return JSON, but a successful PUT may instead return an empty body, often with status 204 No Content. Check the response content type before decoding JSON, and treat an empty body as a valid response rather than a parsing error.

content_type = response.headers.get("Content-Type", "")

if response.content and "application/json" in content_type:
    body = response.json()
    print(body)
elif response.content:
    print(response.text)
else:
    print("empty response body")

Handle errors and verify the server-side change

Call raise_for_status() to turn HTTP error responses into exceptions, and catch transport failures separately. A timeout is ambiguous: the server may have committed the update even if the client never received the response. Do not blindly retry a timed-out write when the operation has side effects beyond replacing the resource.

try:
    with requests.Session() as session:
        response = session.send(prepared, timeout=(3.05, 10))
        response.raise_for_status()
except requests.exceptions.HTTPError as exc:
    response = exc.response
    print("HTTP error:", response.status_code)
    print("body:", response.text)
except requests.exceptions.Timeout as exc:
    print("request timed out; server-side outcome is unknown:", exc)
except requests.exceptions.RequestException as exc:
    print("request failed:", exc)
else:
    print("PUT accepted:", response.status_code)

A successful status code confirms what the endpoint reported, not necessarily that every field now has the intended value. Read the resource back when the API permits it, then compare the fields the update was meant to change. APIs may normalize values or apply changes asynchronously, so account for their documented representation and consistency guarantees.

try:
    with requests.Session() as session:
        check = session.get(url, headers=headers, timeout=(3.05, 10))
        check.raise_for_status()
        current = check.json()

    mismatches = {
        key: {"expected": value, "actual": current.get(key)}
        for key, value in payload.items()
        if current.get(key) != value
    }

    if mismatches:
        print("server state differs:", mismatches)
    else:
        print("verified:", current)
except requests.exceptions.RequestException as exc:
    print("could not verify server state:", exc)
except ValueError as exc:
    print("verification response was not valid JSON:", exc)

Source: https://www.pythonfaq.net/how-to-send-put-requests-using-requests-put-in-python/


You might also like this video

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply