杰瑞科技汇

python request put

Of course! Here is a comprehensive guide on how to use Python's requests library to make PUT requests.

python request put-图1
(图片来源网络,侵删)

What is a PUT Request?

A PUT request is used to update an existing resource on a server. Think of it like replacing an entire document in a file cabinet. You give the server a complete new version, and it replaces the old one entirely.

  • Use Case: Updating a user's profile, modifying a product's details, or replacing a file.
  • Idempotent: If you send the same PUT request multiple times, the result will always be the same. The resource will just be updated to that same state.

Prerequisites: Install the requests Library

If you don't have the requests library installed, open your terminal or command prompt and run:

pip install requests

Basic Syntax of a PUT Request

The core of the PUT request in requests is the requests.put() method. Its signature is very similar to requests.post().

import requests
# The URL of the resource you want to update
url = 'https://api.example.com/items/1' 
# The new, complete data for the resource (as a dictionary)
payload = {
    'name': 'Updated Widget',
    'quantity': 50,
    'price': 19.99
}
# (Optional) Headers to send, like Content-Type
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}
# Make the PUT request
response = requests.put(url, json=payload, headers=headers)
# Check the response
print(f"Status Code: {response.status_code}")
print(f"Response Body: {response.json()}")

Key Parameters Explained:

  • url: The endpoint of the resource you are updating.
  • data or json: This is where you send the new data for the resource.
    • json=payload (Recommended for APIs): If you pass a Python dictionary to the json parameter, requests will automatically:
      1. Serialize the dictionary into a JSON string.
      2. Set the Content-Type header to application/json.
    • data=payload (For form data): If you are sending data as application/x-www-form-urlencoded, use the data parameter. requests will encode it for you.
  • headers: A dictionary of HTTP headers to send with the request. Common headers include Authorization, Content-Type, and Accept.
  • params: For adding query parameters to the URL (e.g., ?key=value).
  • timeout: (Optional) A number that specifies how many seconds to wait for the server to send data before giving up.

Complete Example: Updating a User Profile

Let's imagine we have a simple REST API for managing users. We want to update the user with ID 123.

python request put-图2
(图片来源网络,侵删)

Scenario:

  • API Endpoint: https://jsonplaceholder.typicode.com/users/123
  • Action: Update the user's name and email.
  • New Data: Name should be "John Doe Smith", email should be "john.doe.smith@example.com".

Here is the full Python script to perform this action.

import requests
import json # Used for pretty-printing the JSON response
# 1. Define the API endpoint for the specific user we want to update
# We are using JSONPlaceholder, a free fake API for testing.
url = "https://jsonplaceholder.typicode.com/users/123"
# 2. Define the new data for the user
# This will completely replace the existing user object.
updated_user_data = {
    "id": 123,
    "name": "John Doe Smith",
    "username": "johndoe",
    "email": "john.doe.smith@example.com",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
        "name": "Romaguera-Crona",
        "catchPhrase": "Multi-layered client-server neural-net",
        "bs": "harness real-time e-markets"
    }
}
# 3. Set the headers
# It's good practice to specify the content type as JSON.
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json"
}
print(f"Sending PUT request to: {url}")
print(f"With data: {json.dumps(updated_user_data, indent=2)}")
print("-" * 30)
# 4. Make the PUT request
try:
    response = requests.put(url, data=json.dumps(updated_user_data), headers=headers)
    # 5. Check the response
    # Raise an exception for bad status codes (4xx or 5xx)
    response.raise_for_status()
    # The response body contains the updated resource
    updated_user = response.json()
    print(f"Successfully updated user!")
    print(f"Status Code: {response.status_code}")
    print("Updated User Details:")
    print(json.dumps(updated_user, indent=2))
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
except requests.exceptions.RequestException as err:
    print(f"An error occurred: {err}")

Running this script will produce output similar to this:

Sending PUT request to: https://jsonplaceholder.typicode.com/users/123
With data: {
  "id": 123,
  "name": "John Doe Smith",
  "username": "johndoe",
  "email": "john.doe.smith@example.com",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
------------------------------
Successfully updated user!
Status Code: 200
Updated User Details:
{
  "id": 123,
  "name": "John Doe Smith",
  "username": "johndoe",
  "email": "john.doe.smith@example.com",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

Note: In the example above, we manually used json.dumps() to serialize the dictionary. A more concise way is to use the built-in json parameter of requests.put(), like this: response = requests.put(url, json=updated_user_data, headers=headers). This achieves the same result and is generally preferred.

python request put-图3
(图片来源网络,侵删)

PUT vs. PATCH: An Important Distinction

It's crucial to understand the difference between PUT and PATCH.

Feature PUT (Replace) PATCH (Partial Update)
Purpose Replaces the entire resource with the new data. Updates only the fields provided in the request.
Data Sent The complete, new representation of the resource. Only the fields that need to be changed.
Idempotent Yes. Multiple identical requests have the same effect. Not necessarily. The effect can change if you apply patches in sequence.
Analogy Replacing an entire chapter in a book with a new chapter. Editing a few sentences in that same chapter.

When to use which:

  • Use PUT when you have the complete new object and want to ensure the server has that exact state. For example, a form where a user edits all their profile fields at once.
  • Use PATCH when you only want to change a few fields. For example, changing a user's password or updating a single product's price without sending all other product details.

The requests library makes PATCH requests just as easy:

# Example of a PATCH request
import requests
url = "https://api.example.com/products/99"
# We only want to update the price
partial_data = { "price": 29.99 }
response = requests.patch(url, json=partial_data)
print(f"Status Code: {response.status_code}")
print(f"Updated Product: {response.json()}")
分享:
扫描分享到社交APP
上一篇
下一篇