Back to Blogs

Blog

REST API: PUT vs PATCH - When to Use Each Update Method

written by
Dhayalan Subramanian
Associate Director - Product Growth at DigitalAPI

Updated on: 

TL;DR

1. PUT replaces an entire resource; PATCH applies partial modifications to a resource.

2. Both PUT and PATCH methods are designed to be idempotent, ensuring consistent results upon multiple identical requests.

3. Choosing between PUT and PATCH depends on whether clients can send a full, valid representation of the resource or only the changes.

4. JSON Patch and JSON Merge Patch are common, standardized formats for specifying partial updates with PATCH.

5. Correct usage leads to more efficient network usage, clearer API semantics, and simplified client-side logic.

Crafting efficient and intuitive APIs often hinges on mastering the subtleties of HTTP methods, especially when it comes to updating resources. While `GET` and `POST` are relatively straightforward for retrieving and creating data, the choice between `PUT` and `PATCH` for modifying existing resources can often be a source of confusion. This decision is more than just a technical detail; it impacts network efficiency, data integrity, and the overall developer experience. Understanding the fundamental distinctions between these two update methods is crucial for designing robust, scalable, and semantically correct RESTful APIs. Delving into their specific use cases, characteristics like idempotency, and the implications of their implementation will empower you to make informed choices that streamline your API interactions and enhance the reliability of your data updates.

The Essence of RESTful Update Operations

In the realm of API design, an update operation typically involves a client sending data to a server to modify an existing resource. The HTTP specification provides two primary methods for this purpose: `PUT` and `PATCH`. While both are used to alter server-side data, they operate with different semantic intentions and expectations regarding the request payload. Choosing the correct method is fundamental to adhering to REST principles, ensuring clarity in API contracts, and optimizing communication between client and server. A well-designed API leverages these distinctions to make interactions predictable, efficient, and resilient, which are hallmarks of REST API best practices.

HTTP PUT: The Complete Overwrite

The `PUT` method is used to replace a target resource's current representations with the content of the request payload. Think of it as a complete swap. When a client sends a `PUT` request, it is essentially saying, "Here is the *entire* new state of this resource; please replace whatever you currently have with this."

Key Characteristics of PUT:

  • Full Replacement: The client must send a complete representation of the resource, including any fields that are not being modified. If a field is omitted from the `PUT` request, the server is expected to either set that field to its default value, null, or remove it from the resource, effectively overwriting the previous state.
  • Idempotent: `PUT` is inherently idempotent. This means that making the same `PUT` request multiple times will have the exact same effect on the server as making it once. For example, if you `PUT` an object with `id=1` and specific data, repeating that `PUT` operation will simply ensure `id=1` has that specific data, without creating duplicates or side effects. This property is crucial for reliability in networked environments where requests might be retried.
  • Can Create: If the resource identified by the URI does not exist, and the client provides a full representation, `PUT` can be used to create that resource. In this scenario, the server would respond with `201 Created`. However, it's more common to use `POST` for creation when the client doesn't dictate the resource's URI.
  • Requires Full Resource Knowledge: The client must have a complete understanding of the resource's structure and be able to provide all necessary data, even for fields that remain unchanged.

Example Scenario for PUT:

Imagine an API for managing user profiles. A `User` resource might have fields like `id`, `firstName`, `lastName`, `email`, `address`, and `phone`. If a client wants to update a user's `firstName` and `lastName`, a `PUT` request would require sending the entire user object, even if `email`, `address`, and `phone` remain unchanged.

Request:

PUT /users/123
Content-Type: application/json

{
   "id": "123",
   "firstName": "Jane",
   "lastName": "Doe",
   "email": "jane.doe@example.com",
   "address": "123 Main St",
   "phone": "555-1234"
}

If the client only sent `{"firstName": "Jane", "lastName": "Doe"}` in a `PUT` request, the server would likely wipe out or nullify the `email`, `address`, and `phone` fields for user `123` because they were omitted from the *full* representation provided.

HTTP PATCH: The Surgical Strike

The `PATCH` method is used to apply partial modifications to a resource. Unlike `PUT`, which demands a complete resource representation, `PATCH` allows clients to send only the specific changes they want to make. This makes `PATCH` ideal for granular updates where only a few fields need to be altered without affecting others.

Key Characteristics of PATCH:

  • Partial Modification: The client sends a payload containing only the instructions or data for the fields that need to be changed. The server applies these changes to the existing resource, leaving unspecified fields untouched.
  • Idempotent (with careful implementation): While `PATCH` is not inherently idempotent in the same way as `PUT` (where simply repeating the request always yields the same state), it *can* be made idempotent through careful server-side implementation. If a `PATCH` request specifies a clear, idempotent set of changes (e.g., "set `firstName` to 'Jane'"), then repeating it will have the same effect. However, if the `PATCH` operation is defined as "increment `viewCount`," repeating it would have different effects, making it non-idempotent. The HTTP methods specification notes that `PATCH` is not necessarily idempotent, and server implementers must ensure idempotency if required.
  • Never Creates: `PATCH` is strictly for modifying existing resources. It cannot be used to create a new resource. If the resource identified by the URI does not exist, the server should respond with `404 Not Found`.
  • Efficiency: `PATCH` is often more efficient than `PUT` in terms of bandwidth, as it sends only the delta (the changes) rather than the entire resource. This is particularly beneficial for large resources or connections with limited bandwidth.
  • Requires Server-Side Logic: The server needs to implement logic to correctly apply the partial changes specified in the `PATCH` payload to the existing resource. This can be more complex than the simple overwrite logic required for `PUT`.

Example Scenario for PATCH:

Using the same `User` resource example, if the client only wants to update a user's `firstName` and `lastName`, a `PATCH` request would only send those specific fields:

Request:

PATCH /users/123
Content-Type: application/json

{
   "firstName": "Jane",
   "lastName": "Doe"
}

In this `PATCH` scenario, the server would update only `firstName` and `lastName` for user `123`, leaving `email`, `address`, and `phone` untouched. This is the primary distinction that makes `PATCH` powerful for granular updates.

Standardizing Partial Updates: JSON Patch and JSON Merge Patch

Because `PATCH` allows for partial modifications, the format of the request payload is critical. Unlike `PUT`, where the payload is simply the full representation of the resource, `PATCH` needs a way to describe *what* changes should be applied. Two common, standardized formats address this:

1. JSON Patch (RFC 6902)

Description: JSON Patch defines a JSON document that expresses a sequence of operations to apply to a target JSON document. It's a precise, instruction-based format that supports operations like `add`, `remove`, `replace`, `move`, `copy`, and `test`.

Precision: It offers granular control, allowing clients to modify specific elements within an array, add fields, remove fields, or even test for existing values before applying a change.

Example: To change a user's `firstName` and `lastName`:

PATCH /users/123
Content-Type: application/json-patch+json

[
   { "op": "replace", "path": "/firstName", "value": "Jane" },
   { "op": "replace", "path": "/lastName", "value": "Doe" },
   { "op": "remove", "path": "/email" }
]

Use Case: Ideal when precise, fine-grained control over modifications is needed, or when changes involve complex structures like arrays. Often used in scenarios where the client needs to convey a "diff" from a known state.

2. JSON Merge Patch (RFC 7386)

Description: JSON Merge Patch is a simpler format where the request body is a partial JSON document. The server then "merges" this partial document with the existing resource. If a field exists in both, the value from the `PATCH` document replaces the existing value. If a field is present in the `PATCH` document but not in the original, it's added. If a field is explicitly set to `null` in the `PATCH` document, it's removed from the resource (or set to `null` if `null` is a valid value for that field).

Simplicity: It's easier to generate from a client's perspective, often just sending the fields that have changed.

Example: To change a user's `firstName` and `lastName`:

PATCH /users/123
Content-Type: application/merge-patch+json

{
   "firstName": "Jane",
   "lastName": "Doe",
   "email": null // This would remove or nullify the email field
}

Use Case: Best for simple updates where fields are added, updated, or removed, and the primary concern is sending a subset of data. It's less suitable for array manipulations or very specific, instruction-based modifications.

While using a generic `application/json` content type for `PATCH` requests is common and often implies JSON Merge Patch semantics, explicitly using `application/json-patch+json` or `application/merge-patch+json` as the `Content-Type` header clarifies the intent and processing method for the server.

PUT vs. PATCH: A Direct Comparison

To solidify the understanding of these two update methods, here's a direct comparison of their key attributes:

Attribute PUT PATCH
Purpose Replaces the entire resource. Applies partial modifications to the resource.
Payload Requirement Requires a complete representation of the resource. Requires only the fields or instructions for the changes.
Idempotency Inherently idempotent. Repeated requests result in the same state. Can be idempotent, but depends on server implementation. Not guaranteed by default.
Resource Creation Can create a resource if the URI does not exist and a full representation is provided. Though POST is more commonly used for creation. Cannot create a resource. Only modifies existing ones.
Server Logic Complexity Simpler server logic. Typically overwrites existing data. More complex server logic. Must merge or apply changes and handle conflicts.
Bandwidth Usage Potentially higher bandwidth usage since the full resource is sent. Generally lower bandwidth usage since only the delta is sent.
Common Content Types application/json, application/xml, etc. application/json, application/json-patch+json, application/merge-patch+json

Strategic Choice: When to Opt for PUT

Choosing `PUT` is appropriate when the client's intent is to completely replace an existing resource with a new, authoritative representation. Consider these scenarios:

  • Client Possesses Full Resource State: If the client application always has a complete, up-to-date representation of the resource (e.g., after a `GET` request), and can send it back in its entirety, `PUT` simplifies client and server logic. This is common in forms where all fields are loaded, modified, and then saved.
  • Simpler Server-Side Logic: The server's job for a `PUT` operation is relatively straightforward: delete the old resource (conceptually) and store the new one. This reduces the complexity of handling partial updates and potential merge conflicts.
  • Overwriting is Acceptable: When omitting fields in the `PUT` request should explicitly lead to those fields being reset, nulled, or removed from the resource. This implies that the client's payload is the single source of truth for the resource's state.
  • Strict Data Integrity for the Whole Resource: If the resource's integrity depends on all its fields being present and valid in every update, `PUT` enforces this by requiring a complete representation.
  • Resource Creation (with client-defined URI): While `POST` is typical for resource creation, `PUT` is suitable when the client explicitly determines the URI for the new resource. For example, uploading a file to a specific path: `PUT /files/document.pdf`.

The key takeaway for `PUT` is that the request payload is the *definitive* state of the resource you want to exist on the server. Anything not included is implicitly considered "gone" or "reset."

Strategic Choice: When to Opt for PATCH

`PATCH` shines when the client needs to apply specific, incremental changes to a resource without providing its full representation. It's the method of choice for targeted updates:

  • Partial Updates: When clients only have a subset of a resource's data that needs modification, `PATCH` prevents unnecessary data transfer and avoids the risk of inadvertently altering other fields. This is common in user settings, status updates, or toggling features.
  • Bandwidth Efficiency: For large resources, sending only the changes can significantly reduce network traffic, making the API more responsive and cost-effective, especially on mobile networks or for frequently updated data.
  • Independent Field Updates: If different clients or parts of an application can update different fields of the same resource independently, `PATCH` allows them to do so without knowing or affecting other fields. For example, one client updates a user's `address`, while another updates their `profilePicture`.
  • Complex Resource Structures: When a resource has many fields, some nested deeply, `PATCH` with formats like JSON Patch provides a powerful way to make precise changes without the complexity of re-transmitting the entire structure.
  • Concurrent Updates: While both `PUT` and `PATCH` need careful handling of concurrent updates, `PATCH` can sometimes simplify the resolution of conflicts if the operations are narrowly scoped (e.g., "increment this counter" vs. "replace the entire object").

The crucial distinction for `PATCH` is that the request payload is an *instruction set* or a *delta* describing how to transform the current state of the resource. The server must intelligently apply these changes, preserving unmentioned fields.

The Idempotency Imperative: Ensuring Reliability

Idempotency is a cornerstone of robust API design, especially for update operations. An operation is idempotent if executing it multiple times produces the same result as executing it once. This property is vital for systems operating over unreliable networks, where requests might be retried due to timeouts or other transient failures.

  • PUT's Idempotency: The `PUT` method is naturally idempotent because its semantic is "replace this resource with this exact state." If you send the same `PUT` request twice, the resource will simply be replaced with the identical data twice, resulting in the same final state. This simplifies client-side retry logic, as clients can safely resend `PUT` requests without worrying about unintended side effects like duplicate resource creation or inconsistent states.
  • PATCH's Idempotency: The idempotency of `PATCH` is more nuanced. If a `PATCH` request describes a specific, absolute change (e.g., `{"op": "replace", "path": "/status", "value": "completed"}`), then repeating this request will indeed result in the same final state, making it idempotent. However, if a `PATCH` operation is relative (e.g., `{"op": "increment", "path": "/viewCount", "value": 1}`), repeating it will increment the count multiple times, making it non-idempotent. Therefore, when designing `PATCH` endpoints, API developers must explicitly consider and, if necessary, implement logic to ensure idempotency for their specific partial update operations. This can involve using version numbers, ETags, or unique transaction IDs within the `PATCH` payload to prevent applying the same logical change multiple times. For API developers, thorough API testing is essential to confirm the idempotency (or lack thereof) of their `PATCH` implementations.

Ensuring idempotent update operations provides predictability and resilience against network glitches and client-side retry mechanisms, leading to a more stable and reliable API ecosystem.

Enhancing Update Endpoints: Performance and Maintainability

Beyond the core semantics, the choice and implementation of `PUT` and `PATCH` have broader implications for the performance and maintainability of your API.

Caching Strategies:

  • PUT: Since `PUT` replaces the entire resource, it generally invalidates any cached versions of that resource. Proxies and clients must fetch the new representation.
  • PATCH: `PATCH` also invalidates cached representations, as the resource state has changed. However, due to its partial nature, there might be more complex considerations for smart caching mechanisms attempting to merge changes. In practice, both lead to cache invalidation for the modified resource.

Monitoring and Observability:

Correctly distinguishing between `PUT` and `PATCH` in your API monitoring tools can provide clearer insights into how clients are interacting with your API. For example, a high volume of `PUT` requests might indicate clients are sending full resource representations unnecessarily, while complex `PATCH` errors could signal issues with client-side patch generation or server-side merging logic. Using best API monitoring tools can help track these patterns.

Rate Limiting:

Both `PUT` and `PATCH` are typically seen as write operations and should be subject to rate limiting to protect your backend resources from abuse. While `PATCH` might appear lighter on bandwidth, the computational cost on the server for merging changes could be higher, making consistent rate limiting crucial.

Developer Experience:

Clear semantics help developers. When they understand whether to send a full resource or a partial one, they write more efficient and less error-prone client code. Good API developer portal documentation should clearly specify which method to use and what payload formats are expected.

Thoughtful selection of `PUT` or `PATCH` contributes to a more efficient and understandable API that is easier to maintain and scale over time, integrating well with your broader API gateway and API management strategies.

Best Practices for Robust API Update Endpoints

Regardless of whether you choose `PUT` or `PATCH`, adhering to certain best practices will ensure your update endpoints are robust, secure, and developer-friendly.

  1. Consistency is Key: Maintain consistent naming conventions, response structures, and error handling across all your update endpoints. Predictability reduces the learning curve for developers.
  2. Clear Documentation: Explicitly state in your API documentation when to use `PUT` versus `PATCH`. Provide examples for both request and response payloads, especially for `PATCH` with its various formats (JSON Patch, JSON Merge Patch).
  3. Strong Validation: Implement robust input validation for all incoming data to prevent invalid states and security vulnerabilities. This includes type checking, format validation, and business rule validation.
  4. Implement Versioning: As your API evolves, the structure of resources might change. A solid API versioning strategy is essential to ensure older clients continue to function while new features are introduced. Updates often necessitate version changes.
  5. Security First: Always secure your update endpoints with appropriate API authentication and authorization mechanisms. Ensure clients only have permission to modify the resources and fields they are allowed to. Use API security tools and solutions to continuously scan for vulnerabilities.
  6. Concurrency Control: For `PUT` and `PATCH`, implement concurrency control (e.g., using ETags and `If-Match` headers) to prevent lost updates when multiple clients try to modify the same resource simultaneously.
  7. Meaningful Error Messages: Provide clear, actionable error messages with appropriate HTTP status codes (e.g., `400 Bad Request`, `422 Unprocessable Entity` for validation errors, `409 Conflict` for concurrency issues).
  8. Consider API Lifecycle Management: Plan for the evolution and eventual deprecation of update methods or resource structures. Communicate changes proactively to your API consumers.

By following these best practices, you can build update endpoints that are not only functional but also reliable, secure, and a pleasure for developers to integrate with.

FAQs

1. Is PUT always better than PATCH for full resource updates?

`PUT` is semantically correct for full resource updates where the client sends the entire, new state of the resource. It's often simpler to implement on the server side (a direct overwrite). However, if clients frequently lack the full resource state or only need to change a few fields, `PATCH` might be more efficient in terms of bandwidth and can be preferable for targeted updates, even if it adds server-side complexity for merging changes.

2. Can PATCH be used to create a resource?

No, `PATCH` is strictly for modifying an existing resource. If a `PATCH` request is sent to a URI where no resource exists, the server should respond with `404 Not Found`. Resource creation is primarily handled by the `POST` method, or occasionally by `PUT` when the client determines the resource's URI.

3. What happens if I omit a field in a PUT request?

If you omit a field in a `PUT` request, the server is expected to treat that field as if it were explicitly set to `null` or its default value, or even removed, effectively overwriting the previous state. The `PUT` method signifies a *complete* replacement, so any missing data in the payload is considered intentional and will alter the resource accordingly.

4. How do JSON Patch and JSON Merge Patch differ for PATCH requests?

JSON Patch (RFC 6902) is an instruction-based format that specifies a sequence of operations (add, remove, replace, move, copy, test) to apply. It offers precise control, especially for arrays. JSON Merge Patch (RFC 7386) is a simpler, data-driven format where the payload is a partial JSON document that gets merged with the existing resource. If a field is `null` in a JSON Merge Patch, it's typically interpreted as a removal. JSON Patch is more powerful for complex, precise changes, while JSON Merge Patch is easier to generate for simple field updates.

5. Why is idempotency so important for update methods?

Idempotency is crucial because it ensures that performing the same operation multiple times has the same effect as performing it once. In distributed systems, network issues can lead to clients retrying requests without knowing if the original request succeeded. For idempotent methods like `PUT` (and carefully implemented `PATCH`), clients can safely retry without fear of creating duplicate resources, introducing inconsistencies, or causing unintended side effects, thus enhancing the API's reliability and resilience.

Liked the post? Share on:

Don’t let your APIs rack up operational costs. Optimise your estate with DigitalAPI.

Book a Demo

You’ve spent years battling your API problem. Give us 60 minutes to show you the solution.

Get API lifecycle management, API monetisation, and API marketplace infrastructure on one powerful AI-driven platform.