- Key Difference between PUT and PATCH
- What is the PUT Method & How Does It Work?
- Types of PUT Request Methods
- What is the PATCH Method & How Does It Work?
- Types Of PATCH Requests
- Put and Patch Usages
- Conclusion
- Frequently Asked Questions (FAQs)
PUT Vs. PATCH: Key Differences in HTTP Methods for API Updates
In the world of web development, HTTP methods play a crucial role in enabling communication between clients and servers. These methods—such as GET, POST, PUT, and PATCH—define the actions to be performed on resources over the web, guiding how data is requested or modified. In this article, we’ll focus on understanding the difference between PUT and PATCH, two commonly used HTTP methods for updating data.
We’ll explore their definitions, core differences, use cases, and how each impacts server-side operations. Whether you're building RESTful APIs or fine-tuning your backend logic, knowing when to use PUT or PATCH can significantly improve the efficiency and clarity of your application’s architecture. Let’s dive in!
Brief Introduction to PUT
The PUT method is an HTTP request used to update or replace an entire resource on the server. When a PUT request is made, the client sends a complete representation of the updated resource. If the resource does not exist, PUT can also be used to create it. It is idempotent, meaning multiple identical PUT requests will result in the same state of the resource.
Brief Introduction to PATCH
The PATCH method is used for making partial updates to an existing resource. Instead of sending the full data, the client only sends the specific changes that need to be applied. PATCH is more efficient in scenarios where only a few fields need to be updated. While not necessarily idempotent by default, it can be designed to behave idempotently depending on the implementation.
Key Difference between PUT and PATCH
|
Feature |
PUT |
PATCH |
|
Definition |
PUT is an HTTP method used to update or create a resource by replacing the entire data representation. |
PATCH is an HTTP method used to partially update an existing resource, modifying only specific fields. |
|
Operation Type |
Complete replacement – the old resource is entirely replaced with the new data sent. |
Partial update – only the fields present in the request are updated. |
|
Data Required |
Requires all fields of the resource, even if only one has changed. |
Requires only the fields that need to be changed. |
|
Resource Creation |
Can create a new resource if it doesn't exist (when used with PUT URI). |
Cannot create a resource; only updates an existing one. |
|
Idempotency |
PUT is idempotent – sending the same request multiple times gives the same result. |
PATCH may not always be idempotent, depending on the implementation. |
|
Performance Efficiency |
Less efficient, especially with large payloads, as the full resource is sent every time. |
More efficient since only a subset of data is sent and processed. |
|
Bandwidth Usage |
Higher bandwidth usage due to sending the entire resource data. |
Lower bandwidth usage due to smaller, focused payloads. |
|
Typical Use Case |
Ideal for scenarios like updating a user profile completely (name, email, photo, etc.). |
Ideal for scenarios like updating only the email or status field in a user profile. |
|
Request Complexity |
Generally simpler, as it follows a consistent format with full resource data. |
Slightly more complex, may require patch-specific formats like JSON Patch or merge patch. |
|
Example Request (JSON) |
{ "id": 1, "name": "John", "email": "john@example.com" } |
{ "email": "john@example.com" } |
|
Support in APIs |
Fully supported in RESTful APIs; commonly used and well-documented. |
Supported, but implementation varies across APIs; not always available or used. |
|
Risk of Data Loss |
Higher risk if not all fields are correctly passed (missing fields will be removed). |
Lower risk, as untouched fields remain unaffected. |
|
Error Handling |
Errors are easier to debug due to a predictable full resource structure. |
Partial updates can be trickier to validate and debug. |
|
Caching Behavior |
PUT requests can be cached if responses are properly defined. |
PATCH requests are typically not cached due to their partial and variable nature. |
|
Standardization |
Well-defined and widely accepted in REST specifications. |
PATCH is standardized (RFC 5789), but still has less consistent support than PUT. |
What is the PUT Method & How Does It Work?
The HTTP PUT method is one of the key request methods used in RESTful APIs and web services. It is primarily used to update or replace a resource at a specified URI (Uniform Resource Identifier). If the resource does not exist, PUT can also create it, making it an idempotent method—repeated requests with the same data yield the same result.
Characteristics & Functions of the PUT Method
Full Resource Replacement: PUT replaces the entire existing resource with the new one provided in the request body. If a field is missing in the payload, it will be removed from the server-side resource.
Idempotent Nature: Multiple identical PUT requests will not change the result beyond the initial request. This makes it predictable and reliable, especially in scenarios where network interruptions can cause repeated requests.
URI-Specific: The PUT method requires a full URI. For example, sending a PUT request to /users/101 with new user data will completely overwrite the user with ID 101.
Used for Updates or Creation: Although primarily used to update existing resources, PUT can also create a resource if it does not already exist at the given URI, commonly referred to as an "upsert" operation.
Requires Complete Data: PUT expects the client to send the entire representation of the resource, not just the changes. This makes it different from the PATCH method, which supports partial updates.
Stateless Communication: Like other HTTP methods, PUT operates in a stateless manner. Each request must contain all the necessary data, as the server does not retain information between requests.
Example Use Case: If a client sends a PUT request to /products/55 with new product information (name, price, category), the server will completely replace the existing product with ID 55 using the data in the request.
Working Mechanism of the PUT Method
Client Sends Request with Full Data
- The client initiates a PUT request to a specific URI.
- The request body contains the entire representation of the resource to be updated or created.
URI Must Be Known
- The URI (e.g., /users/123) must explicitly identify the resource that the client wants to replace or create.
- If the resource exists at that URI, it will be updated; if it doesn’t, a new one will be created.
Server Receives & Validates Request
- The server receives the PUT request and validates the URI and request body.
- It checks whether the resource exists and if the data provided is valid (e.g., correct data types, required fields, etc.).
Resource is Replaced
- If the resource exists, the server replaces the entire resource with the new data from the request body.
- Any existing fields not present in the new payload will be deleted.
Resource is created (if not found)
- If the resource doesn’t exist at the specified URI, the server can create a new one using the data in the request body.
- This is known as upserting (update or insert).
Response is Sent Back
Upon successful completion, the server responds with:
- 200 OK if the resource was updated.
- 201 Created if the resource was newly created.
- 204 No Content if no response body is returned.
If there’s an issue (like invalid data or a permission error), an appropriate error code like 400 or 403 is returned.
Idempotency Ensured
If the same PUT request is sent again with identical data, the result on the server remains unchanged, ensuring idempotent behavior.
Syntax
requests.put(url, params={key: value}, **args)
Parameters:
- url: The target endpoint.
- data: Dictionary or string to be sent in the body (often in form or JSON data).
- args: Optional parameters like headers, authentication, timeout, etc.
Installation
To use the requests module, we need to first install it using this command:
pip install requests
Example of Making a PUT Request
In this example, we are going to make a real PUT Request using httpbin.org, a public testing API:
import requests
res = requests.put('https://httpbin.org/put', data={'key': 'value'})
print("Status Code:", res.status_code)
print("Response Body:", res.content.decode())
Explanation:
- requests.put() sends the PUT request to the specified URL.
- data parameter inside requests.put() is used to pass the key-value data to be updated or created on the server.
- print(r) displays the response object, including the HTTP status code (e.g., 200 for success).
- print(r.content) prints the response body returned by the server after processing the PUT request.
How PUT Updates an Entire Resource (Working)
The PUT method is designed to completely replace a resource at a given URI. Here's how the process works:
Full Payload Required
- PUT expects the entire representation of the resource to be included in the request body.
- Any fields missing from the payload will be considered removed from the updated resource.
Resource Identification by URI
- The request is sent to a specific URI (e.g., /products/45), which identifies the exact resource to update.
- PUT does not search or merge; it simply targets the given URI for replacement.
Overwrite Operation
- The server overwrites the existing resource with the new one provided in the request.
- It's like replacing the whole object/file with a new version.
Idempotency Maintained
- Sending the same PUT request multiple times will not change the state after the first request—it ensures consistent updates.
Used for Consistency
- PUT is useful when you want to enforce a specific structure for a resource and avoid partial updates or inconsistencies.
Types of PUT Request
- HTTP Method Type: PUT is a type of HTTP request method used to update or replace an entire resource at a specific URI.
- Nature: It is idempotent, meaning sending the same request multiple times will result in the same resource state.
- Common Use Case: Used to fully replace a resource on the server with the data provided in the request body.
Example of PUT Request in JavaScript (Using Fetch API)
Here’s an example where we update a user’s information using a PUT request:
How It Works:
Endpoint: https://api.example.com/users/101 – specifies the resource (user with ID 101).
Method: PUT – we are replacing the entire resource.
Headers: Set to 'Content-Type': 'application/json' to tell the server we're sending JSON data.
Body: The full user object is sent, not just the changed fields.
If the email field had been omitted in the body, it would be removed from the resource on the server (unlike PATCH, which would leave it unchanged).
Types of PUT Request Methods
The PUT request method is used to update or create a resource at a specified URI. It typically involves replacing the entire resource with the provided data, and there are different types of operations that can be associated with a PUT request.
Here are the key types of requests and behaviors associated with PUT:
Replace Resource (Full Update)
- The most common use of PUT is to replace the entire resource with the new data.
- When a PUT request is sent, the server expects the client to provide the full representation of the resource. If any fields are missing from the request, they may be deleted from the existing resource.
Create Resource (If Not Exists)
- If the resource does not already exist at the specified URI, a PUT request can create it.
- This is a common behavior known as "upsert" (update or insert), where the server either updates the resource if it exists or creates it if it doesn't.
- The server must ensure that the URI is unique to the resource being created, and the resource is created with the provided data.
Idempotent PUT Requests
- PUT requests are idempotent, which means that if the same PUT request is made multiple times with the same data, the result will be the same. The resource will be replaced or created in the same state each time.
- This behavior ensures that the outcome of sending the same PUT request multiple times is predictable and does not result in unintended side effects.
Conditional PUT Requests
- In some cases, PUT requests can be conditional. This means that the request will only be processed if certain conditions are met.
- For example, you may include If-Match or If-None-Match headers to ensure that the resource is updated only if it matches a specific version or does not exist.
PUT with Authentication or Headers
- PUT requests often require authentication to ensure that the client has the right to modify the resource.
- Additionally, PUT requests may include custom headers for things like content type, authorization, or other parameters that control the request.
What is the PATCH Method & How Does It Work?
The PATCH method is an HTTP request method used to apply partial modifications to a resource. Unlike PUT, which replaces the entire resource, PATCH is used to update only specific fields or attributes of a resource. It’s ideal when you only need to change a subset of data without affecting the rest.
PATCH is not necessarily idempotent, meaning repeated requests can result in different outcomes if the operation depends on the current resource state. This method is highly efficient in scenarios where only a small update is needed, as it minimizes data transmission and reduces the risk of accidentally overwriting unchanged data.
Features & Characteristics of the PATCH Method
Partial Update: Only modifies specified fields of a resource rather than replacing the entire resource.
Efficient: Requires less data in the request body and consumes less bandwidth compared to PUT.
Non-Destructive: Leaves the unspecified fields unchanged, preventing data loss.
May Be Non-Idempotent: While often treated as idempotent, it can have different results if applied multiple times (especially in computed updates).
Supports Complex Updates: Can be used with structured formats like JSON Patch (RFC 6902) for advanced field operations.
Common Use Case: Updating a single user field (e.g., just an email address) without affecting the rest of the user data.
Safer for Production Updates: PATCH reduces the risk of accidental overwrites during concurrent operations, making it a good choice in modern APIs.
Working Mechanism of the PATCH Method
Client Sends Request with Partial Data
- The client initiates a PATCH request to a specific URI.
- The request body contains only the partial data that needs to be updated, not the entire resource.
URI Must Be Known
- The URI (e.g., /users/123) identifies the specific resource that the client wants to partially update.
- This URI must be known and valid for the update.
Server Receives and Validates Request
- The server receives the PATCH request and validates the URI and the partial data.
- It checks whether the resource exists and ensures that the provided data is valid (e.g., correct data types, valid fields).
Resource is Partially Updated
- If the resource exists, the server applies the changes specified in the request body to the existing resource.
- Only the fields provided in the PATCH request are updated, while the other fields remain unchanged.
Resource is created (if not found)
- If the resource doesn’t exist at the specified URI, the server may choose to create a new one using the partial data from the request body, but this behavior is not guaranteed.
Response is Sent Back
Upon successful completion, the server responds with:
- 200 OK if the resource was successfully patched.
- 201 Created if a new resource was created (if the resource did not exist and was created).
- 204 No Content if no response body is returned.
In case of an error (e.g., invalid data, missing fields), an appropriate error code like 400 Bad Request or 422 Unprocessable Entity may be returned.
Idempotency (Optional)
- While PATCH requests are generally not idempotent (meaning that sending the same request multiple times may have different results), they can be designed to be idempotent if the server ensures that applying the same changes repeatedly results in the same resource state.
Syntax
requests.patch(url, data={key: value}, **args)
Parameters
- url: The target endpoint (e.g., the URI of the resource to be partially updated).
- data: A dictionary or string containing the partial data to be sent in the request body (often in JSON or form data).
- args: Optional parameters such as headers, authentication, timeout, etc.
Installation
To use the requests module, install it first using the following command:
pip install requests
Working of PATCH for Partial Modifications
Client Sends Partial Data
- The client initiates a PATCH request to a specific resource URI.
- Instead of sending the complete resource data, the client sends only the fields that need to be updated (i.e., the partial data).
- This reduces the amount of data transmitted, making it more efficient when updating only a small part of a resource.
Server Receives the Request
- The server receives the PATCH request and processes the partial data sent in the request body.
- It checks if the fields provided in the PATCH request exist in the resource and if the data is valid.
Resource is Partially Updated
- The server updates only the fields that were specified in the PATCH request, leaving the other fields of the resource unchanged.
- This is different from the PUT method, where the entire resource is replaced with the new data.
No Data is Removed Unless Specified
- Any fields not mentioned in the PATCH request remain unchanged in the resource.
- If the request is incomplete (for example, leaving out certain fields that are required for a valid resource), the server may respond with an error (e.g., 400 Bad Request).
Response Sent Back
- After applying the partial update, the server sends a response back to the client, indicating whether the update was successful.
- The server may return a 200 OK status if the resource was successfully patched or 204 No Content if no body is returned after the update.
Idempotency
- PATCH requests are typically not idempotent. This means if the same PATCH request is sent multiple times, it may lead to different results, depending on how the server handles the partial data.
- However, servers can be designed to handle PATCH requests in an idempotent manner by ensuring that repeated changes don't result in unexpected outcomes.
Types Of PATCH Requests
The PATCH method itself is designed for partial updates to resources, but there are different types or styles of PATCH requests that can be used depending on the context, the application, or how the server processes the request.
Here are some common types or approaches to PATCH requests:
Partial Data Update (Standard PATCH)
- This is the most common type of PATCH request, where only a subset of the resource's fields are updated.
- The client sends only the data that needs to be updated, and the server modifies those specific fields while keeping the rest of the resource unchanged.
PATCH with Operations (e.g., JSON Patch or XML Patch)
- The JSON Patch format allows more fine-grained control over how resources are modified. Instead of sending the updated fields directly, clients can specify a series of operations to apply to the resource.
- JSON Patch uses an array of operation objects, which specify an action (e.g., add, remove, replace) and the target of the operation.
PATCH with Conditional Modifications
- Some PATCH requests may include conditions, specifying that updates should only happen if certain criteria are met. This can be implemented using custom headers or conditional statements in the request body.
- For example, a conditional PATCH request might only succeed if the resource has not been modified since a specific timestamp or version number.
Upsert (Update or Insert)
- In some cases, a PATCH request can be used to "upsert" data, meaning the server will create a new resource if one doesn't exist at the specified URI.
- Typically, an upsert behavior is seen in PUT requests, but servers can be designed to allow upserts in PATCH requests as well, though this is not universally expected.
Merge Patch
- A Merge Patch is a more lenient form of PATCH where the client sends a partial resource that contains the fields to be updated.
- The server merges the changes from the request with the existing resource, replacing only the fields provided in the request.
Patch with Structured Operations (e.g., GraphQL-like Patching)
- In some advanced use cases (like GraphQL or complex APIs), the PATCH request may allow specifying structured or nested data operations, like updating elements in an array or performing more complex data transformations within the resource.
- The client might specify not just the data but also transformations or nested modifications, depending on the server's capability.
PATCH with Validation Rules
- Some servers might support PATCH requests that include validation rules within the request body to ensure that only certain updates are allowed based on predefined rules.
- This could involve sending additional metadata or conditions along with the PATCH request to ensure the resource remains valid after the patch is applied.
Put and Patch Usages
Choosing between PUT and PATCH depends on the nature of the operation you want to perform on the resource. Both methods are used for updating data, but they have different semantics and behaviors that make them suitable for different scenarios. Here's a breakdown of when to use each method:
When to Use PUT?
Full Replacement of a Resource
- Use PUT when you need to replace the entire resource or ensure that the resource is entirely replaced with the new data.
- With PUT, the client typically sends the full representation of the resource, and if any fields are missing from the request, they may be deleted from the resource.
Example: Updating a user's profile where you provide the complete data for the user, and the server will replace the entire profile with the new data, even if only one field has changed. If any field (e.g., address) was not included in the PUT request, it may be removed from the resource.
Resource Creation
- Use PUT if you want to create a resource at a specific URI if it doesn't exist. If the resource exists at the URI, it will be replaced; if not, it will be created.
- This is known as upsert (update or insert).
Example: If the user with ID 123 doesn’t exist, the PUT request will create a new user with that ID.
Idempotent Requests
- PUT is idempotent, meaning that multiple identical PUT requests will have the same effect as a single request. This ensures that if a PUT request is retried (for example, due to network issues), the state of the resource remains consistent.
Example: If you send the same PUT request multiple times, the result will always be the same—no unintended side effects.
When to Use PATCH?
Partial Updates (Partial Resource Modification)
- Use PATCH when you want to make partial updates to a resource. Instead of sending the full resource data, you only send the fields that need to be updated. The server will then apply the changes to the existing resource without affecting the fields that were not included in the request.
- PATCH allows for more efficient updates when you only need to modify a small part of the resource.
Example: Updating only the email of a user profile while leaving the other fields unchanged.
When Full Resource Representation is Unavailable
- If the client does not have the full representation of the resource (perhaps due to memory limitations, or because the client doesn’t need the entire resource), PATCH is a better option since it only requires the client to send the data that needs modification.
More Granular Control with Structured Updates
- PATCH can be used with more advanced techniques (e.g., JSON Patch or Merge Patch) to specify exactly which fields to modify and how to modify them. This is particularly useful when you need fine-grained control over the update process, such as adding, removing, or replacing specific elements.
Less Risk of Overwriting Unintended Data
- PATCH ensures that only the specified fields are modified. There’s no risk of accidentally overwriting or removing data that you don’t intend to change, which can happen with PUT if the full resource isn’t supplied.
Conclusion
Both PUT and PATCH are essential HTTP methods used for updating resources on a server, each serving different purposes based on the nature of the update. PUT is ideal for scenarios where a complete replacement of a resource is required or when creating a new resource at a known URI. It ensures consistency through its idempotent behavior and is typically used when the full representation of the resource is available.
On the other hand, PATCH is best suited for partial updates where only specific fields need to be modified, making it more efficient and less error-prone in cases where the client does not possess the full resource data. Its flexibility allows for targeted changes without affecting untouched data. Ultimately, the choice between PUT and PATCH depends on the specific update requirements, data handling practices, and efficiency considerations of the application. Understanding the differences and appropriate use cases of these methods enables developers to design more effective and RESTful APIs.
Frequently Asked Questions (FAQs)
Q1. Can PATCH requests be used to create resources?
Typically, PATCH is used to modify existing resources and is not intended for creating new ones. According to RFC 5789, if the resource does not exist, the server may create it based on the patch document and server permissions, but this behavior is not guaranteed or standardized.
In practice, PUT is preferred when creating a resource at a known URI, while POST is used when the server determines the URI. Using PATCH for resource creation may result in inconsistent behavior across different APIs and should generally be avoided unless explicitly supported by the server.
Q2. What is the difference between PUT and PATCH?
PUT replaces the entire resource with the data provided by the client. It requires the full updated representation of the resource, and any missing fields may be removed.
PATCH, on the other hand, performs a partial update. It only modifies the specified fields while leaving the rest of the resource unchanged. This makes PATCH more efficient for small updates and safer when the client does not have the complete resource.
Q3. Is PATCH idempotent like PUT?
PUT is always idempotent, meaning repeated identical requests have the same effect as a single request.
PATCH is not guaranteed to be idempotent. It depends on the nature of the patch operation. For example, incrementing a value with PATCH is not idempotent, but replacing a field value can be. Whether or not PATCH is idempotent depends on how the server implements it.
Q4. When should I use PATCH instead of PUT?
Use PATCH when you need to update only specific fields of a resource and want to avoid sending the entire object. It is ideal when:
- Only one or a few attributes need to change.
- The client doesn’t have the full resource data.
- You want to avoid unintentionally deleting data not included in the request.
Use PUT when:
- Replacing or creating an entire resource.
- The client has the full representation of the resource.
- Idempotency and consistency are critical.
Q5. Can PATCH requests use JSON Patch or other formats?
Yes, PATCH requests can use different formats for specifying updates, the most common being:
- JSON Patch (application/json-patch+json): A format based on an array of operations like add, remove, replace, etc.
- JSON Merge Patch (application/merge-patch+json): A simpler approach where fields in the JSON object are merged into the existing resource.
The format used must be supported by the server, and the client must set the correct Content-Type header to indicate the patch document type.
This article was contributed by Johns Joseph, Unstop Intern and Campus Ambassador.
Suggested reads:
- File System Vs. DBMS: Key Differences & Usages Explained in Detail
- HTML Vs. DHTML: Key Differences, Components & Web Development Uses
- Array Vs. Linked List: Key Differences & Usages Explained in Detail
- Hardwired Vs. Microprogrammed Control Unit: Differences & Examples
- Difference between Webpage and Website Explained! (+Similarities)
The writing program is a crew of student writers from arts and sciences, commerce, engineering, and MBA backgrounds. Fueled by caffeine, curiosity, and deadline-induced adrenaline–and driven by an unshakable love for learning–these jugglers turn knowledge into bite-sized brilliance.
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Subscribe
to our newsletter
Comments
Add comment