PUT vs PATCH: Key Differences and When to Use Each
PUT method replaces an entire resource with the data sent, while PATCH updates only specific fields of a resource. PUT is idempotent and expects full data, whereas PATCH is used for partial updates and may be idempotent depending on implementation.Quick Comparison
Here is a quick side-by-side comparison of PUT and PATCH methods in REST APIs.
| Factor | PUT | PATCH |
|---|---|---|
| Purpose | Replace entire resource | Update part of the resource |
| Request Body | Full resource representation | Partial resource data |
| Idempotency | Yes (same request repeated has same effect) | May be idempotent depending on implementation |
| Use Case | Complete update or create resource | Partial update |
| Effect on Missing Fields | Missing fields are removed | Missing fields remain unchanged |
| Typical Response | 200 OK or 204 No Content | 200 OK or 204 No Content |
Key Differences
The PUT method is designed to replace the entire resource at the specified URL. When you send a PUT request, you provide the full new state of the resource. If some fields are missing in the request, they are usually removed or reset on the server. This makes PUT idempotent, meaning sending the same request multiple times results in the same resource state.
On the other hand, PATCH is used to make partial updates to a resource. You only send the fields you want to change, and the server updates those fields without affecting others. Because PATCH modifies parts of the resource, it may be idempotent depending on the implementation. This makes PATCH more efficient when you want to update a few fields without resending the entire resource.
In summary, use PUT when you want to replace or create a resource fully, and use PATCH when you want to update only specific parts of a resource.
PUT Code Example
This example shows how to update a user resource fully using PUT. The entire user data is sent in the request.
import requests url = 'https://api.example.com/users/123' user_data = { 'name': 'Alice Smith', 'email': 'alice@example.com', 'age': 30 } response = requests.put(url, json=user_data) print(response.status_code) print(response.json())
PATCH Equivalent
This example updates only the email field of the user using PATCH. Other fields remain unchanged.
import requests url = 'https://api.example.com/users/123' partial_update = { 'email': 'alice.new@example.com' } response = requests.patch(url, json=partial_update) print(response.status_code) print(response.json())
When to Use Which
Choose PUT when: You want to replace the entire resource or create it if it does not exist. This is useful when you have the full updated data and want to ensure the resource matches exactly.
Choose PATCH when: You want to update only certain fields without affecting the rest of the resource. This is efficient for small changes and avoids sending unnecessary data.