Recent from talks
Contribute something
Nothing was collected or created yet.
PATCH (HTTP)
View on Wikipedia| HTTP |
|---|
| Request methods |
| Header fields |
| Response status codes |
| Security access control methods |
| Security vulnerabilities |
In computing, the PATCH method is a request method in HTTP for making partial changes to an existing resource.[1] The PATCH method provides an entity containing a list of changes to be applied to the resource requested using the HTTP Uniform Resource Identifier (URI).[1] The list of changes are supplied in the form of a PATCH document.[1] If the requested resource does not exist then the server may create the resource depending on the PATCH document media type and permissions.[1] The changes described in the PATCH document must be semantically well defined but can have a different media type than the resource being patched.[2] Languages such as XML or JSON can be used in describing the changes in the PATCH document.
History of PATCH
[edit]As per the semantics defined in the HTTP protocol, the GET, PUT, and POST methods need to use a full representation of the resource. The PUT method which can be used for resource creation or replacement is idempotent and can be used only for full updates. The edit forms used in conventional Ruby on Rails application need to create new resources by applying partial updates to a parent resource. Due to this requirement, the PATCH method was added to the HTTP protocol in 2010.[3][4]
PUT vs PATCH vs POST
[edit]HTTP is the foundation of data communication for the World Wide Web. It is a request-response protocol which helps users communicate with the server to perform CRUD operations. HTTP defines a number of request methods such as PUT, POST and PATCH to create or update resources.[5]
The main difference between the PUT and PATCH method is that the PUT method supplies a modified version of the requested resource which replaces the original version of the resource, whereas the PATCH method supplies a set of instructions to modify the resource. If the PATCH document is larger than the size of the new version of the resource sent by the PUT method then the PUT method is preferred.[1]
The POST method can be used for sending partial updates to a resource. The main difference between the POST and PATCH methods is that the POST method can be used only when it is written to support the applications or the applications support its semantics whereas the PATCH method can be used in a generic way and does not require application support. If the outcome of using the PATCH method is not known then the POST method is preferred.[1][6]
Patching resources
[edit]The PATCH method is atomic.[1] Either all the changes specified by the PATCH method are applied or none of the changes are applied by the server.[1] There are many ways of checking whether a patch was applied successfully. For example, the 'diff' utility can be applied to the older version and newer version of a file to find the differences between them.[1]
A cached PATCH response is considered stale. It can only be used for the GET and HEAD requests that may follow the PATCH request.[1]
The entity headers in the PATCH document are only applicable to the PATCH document and cannot be applied to the requested resource.[1]
There is no standard format for the PATCH document and it is different for different types of resources. The server has to check whether the PATCH document received is appropriate for the requested resource.[1]
A JSON Patch document would look like
[
{ "op": "add", "path": "/count", "value": 1 }
]
"op" represents the operation performed on the resource. "path" represents the resource being modified. "value" represents the amount being added to the existing resource.[7] Before applying the changes in the PATCH document, the server has to check whether the PATCH document received is appropriate for the requested resource. If the PATCH request succeeds then it returns a 204 response.[8]
A XML PATCH document would look like
<add sel="doc/user[@email='xyz@abc.com']" type="@address">
ABC Road
</add>
The element <user> is located using the 'email' attribute. A new attribute 'address' with the value "ABC Road" is added to the <user> element.[9]
Example
[edit]A simple PATCH request example
PATCH /example.txt HTTP/1.1
Host: www.example.com
Content-Type: application/example
If-Match: "c0b42b66e"
Content-Length: 120
[Changes: the patch document containing all the changes that need to be made on the resource example.txt]
Successful PATCH response to existing text file:
HTTP/1.1 204 No Content
Content-Location: /example.txt
ETag: "dd541480"
The response 204 means that the request was processed successfully.[10]
Trade-offs between PUT and PATCH
[edit]Using the PUT method consumes more bandwidth as compared to the PATCH method when only a few changes need to be applied to a resource.[citation needed] But when the PATCH method is used, it usually involves fetching the resource from the server, comparing the original and new files, creating and sending a diff file. On the server side, the server has to read the diff file and make the modifications. This involves a lot of overhead compared to the PUT method.[11] On the other hand, the PUT method requires a GET to be performed before the PUT and it is difficult to ensure that the resource is not modified between the GET and PUT requests.
Caution
[edit]The PATCH method is not "safe" in the sense of RFC 2616: it may modify resources, not necessarily limited to those mentioned in the URI.[1]
The PATCH method is not idempotent. It can be made idempotent by using a conditional request.[1] When a client makes a conditional request to a resource, the request succeeds only if the resource has not been updated since the client last accessed that resource. This also helps in preventing corruption of the resource since some updates to a resource can only be performed starting from a certain base point.[1]
Error handling
[edit]A PATCH request can fail if any of the following errors occur:
Malformed patch document
[edit]The server returns a 400 (Bad request) response if the PATCH document is not formatted as required.[1]
Unsupported patch document
[edit]The server returns a 415 (Unsupported Media Type) response with an Accept-Patch response header containing supported media types when the client sends a patch document in a format not implemented by the server. This informs the client that the PATCH document sent by the client cannot be applied to the requested resource.[1]
Unprocessable request
[edit]The server returns a 422 (Unprocessable Entity) response when the server understands the PATCH document but is unable to modify the requested resource either because it causes the resource to become invalid or it results in some other error state.[1]
Resource not found
[edit]The server returns a 404 (Not Found) response when the PATCH document cannot be applied to a non-existent resource.[1]
Conflicting state
[edit]The server returns a 409 (Conflict) response when the server cannot apply a patch for the current state of the resource.[1]
Conflicting modification
[edit]The server returns a 412 (Precondition Failed) response when the precondition supplied by the client using the If-Match or If-Unmodified-Since header fails. If no precondition is supplied and there is a conflicting modification then the server returns a 409 (Conflict) response.[1]
Concurrent modification
[edit]The server returns a 409 (Conflict) response if the PATCH requests to a certain resource need to be applied in a certain order and the server is not able to handle concurrent PATCH requests.[1]
Security considerations
[edit]The PATCH request needs to use mechanisms such as conditional requests using Etags and the If-Match request header to ensure that data is not corrupted while patching.[1] In case of a failure of a PATCH request or failure of the channel or a timeout, the client can use a GET request to check the state of the resource.[1] The server has to ensure that malicious clients do not use the PATCH method for consuming excessive server resources.[1]
References
[edit]- ^ a b c d e f g h i j k l m n o p q r s t u v w x y Dusseault, L.; Snell, J. (2010). "PATCH Method for HTTP". doi:10.17487/RFC5789. S2CID 42062521. Retrieved 2015-09-12.
{{cite journal}}: Cite journal requires|journal=(help) - ^ "Don't Patch Like An Idiot". Don't Patch Like An Idiot. 14 February 2014. Retrieved 16 September 2015.
- ^ RFC 5789
- ^ "History of PATCH". weblog.rubyonrails.org. Retrieved 25 September 2015.
- ^ "Hypertext Transfer Protocol -- HTTP/1.1". Retrieved 13 September 2015.
- ^ "Why PATCH is Good for Your HTTP API". Why PATCH is Good for Your HTTP API. Retrieved 16 September 2015.
- ^ "JSON Patch - draft-ietf-appsawg-json-patch-08". Ietf Datatracker. Retrieved 13 September 2015.
- ^ "PATCH". MDN Web Docs. Retrieved 2018-10-11.
- ^ Urpalainen, J. (2008). "XML RFC". tools.ietf.org. doi:10.17487/RFC5261. Retrieved 25 September 2015.
- ^ "PATCH". MDN Web Docs. Retrieved 2018-10-12.
- ^ Darren (7 May 2014). "REST API Best Practices 3: Partial Updates - PATCH vs PUT". www.blogger.com. Retrieved 13 September 2015.
PATCH (HTTP)
View on Grokipediaapplication/merge-patch+json[2] or application/json-patch+json[3])—that describes how the server should modify the target resource.[1]
Unlike idempotent methods such as PUT, PATCH is neither safe nor idempotent by default, meaning repeated applications may result in different outcomes depending on the patch semantics, and servers are required to apply the changes atomically to ensure consistency.[1] To support conditional patching and avoid conflicts, PATCH requests can include preconditions like the If-Match header with entity tags (ETags).[1] Servers advertise PATCH support via the Accept-Patch response header in OPTIONS requests, specifying allowed media types for patch documents.[1] Common error responses include 400 (Bad Request) for malformed patches, 409 (Conflict) for precondition failures, and 422 (Unprocessable Entity) for semantic issues in the patch.[1]
Introduced in 2010 to address limitations in earlier HTTP methods for partial updates, PATCH has become a standard in RESTful APIs for scenarios like modifying user profiles or configuration files without transmitting full datasets, promoting bandwidth efficiency and reducing error risks in distributed systems. While the method itself is version-agnostic and supported in HTTP/1.1 and later versions including HTTP/2 and HTTP/3, its adoption relies on standardized patch formats such as JSON Patch (RFC 6902)[3] for JSON resources or Merge Patch (RFC 7396)[2] to ensure interoperability across implementations.
Definition and Purpose
Formal Definition
The HTTP PATCH method is a request method in the Hypertext Transfer Protocol (HTTP) that enables partial modifications to a resource identified by the Request-URI. Specifically, "the PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI."[4] The request entity contains a "patch document," which consists of a set of instructions describing how the resource currently residing on the origin server should be modified, rather than providing a complete replacement representation.[4] This document is identified by a media type, but no default format is mandated, allowing flexibility in how changes are specified.[4] Upon receiving a PATCH request, the server is required to apply the changes to the resource in an atomic manner, ensuring that the resource is never left in a partially modified state.[4] A successful response is indicated by a 2xx status code, such as 204 No Content, confirming that the modifications have been fully applied.[4] Unlike safe methods like GET, PATCH is neither safe nor idempotent by default, meaning repeated invocations may result in different outcomes depending on the patch document's semantics; however, idempotency can be achieved through conditional requests, such as using the If-Match header.[4] Servers claiming support for PATCH must handle it appropriately for the resource's media type, but the precise implementation of the changes remains server-defined, without requiring adherence to a specific patch format.[4] In distinction from full replacement methods like PUT, where the enclosed entity represents the complete modified version of the resource, PATCH focuses on incremental updates via targeted instructions, making it suitable for scenarios where only portions of the resource need alteration.[4] This semantic difference underscores PATCH's role in enabling efficient, partial resource management without necessitating the transmission of the entire resource state.[4]Intended Use Cases
The PATCH method is particularly suited for partial updates to large resources, where only specific fields or sections need modification without requiring the transmission or replacement of the entire resource representation. For instance, in a REST API managing user profiles, an application might use PATCH to update a single attribute, such as an email address or phone number, thereby avoiding the inefficiency of resending the full document containing biographical details, preferences, and other unchanged data.[5][6] In bandwidth-constrained environments like mobile applications or Internet of Things (IoT) devices, PATCH minimizes data transfer by conveying only the differential changes, reducing latency and conserving limited network resources compared to methods that demand complete payloads. This approach is especially beneficial for battery-powered devices that frequently synchronize small status updates, such as sensor readings or configuration tweaks, without the overhead of full resource fetches or replacements.[7] PATCH finds application in versioning systems where full resource replacement via other methods could introduce risks, such as overwriting concurrent modifications or violating optimistic locking mechanisms. By supporting conditional requests (e.g., via If-Match headers), it enables safe, targeted alterations to versioned entities, like appending entries to audit logs or incrementally revising database records without a predefined baseline state.[5] Real-world applications include updating task statuses in workflow management systems, where PATCH allows atomic changes to progress indicators (e.g., from "pending" to "approved") across distributed services without disrupting the broader workflow state. Similarly, in microservices architectures, it facilitates precise configuration modifications, such as adjusting a single parameter in a service's settings, ensuring modularity and reducing inter-service data exchange.[8][9]Historical Background
Early Proposals
The development of the HTTP PATCH method began with an initial Internet-Draft authored by Lisa Dusseault in November 2003, titled "HTTP PATCH," which proposed a new method to enable partial modifications to existing resources. This draft addressed the shortcomings of the existing PUT method, which required complete resource replacement and often led to inefficiencies or errors when only specific parts needed updating. The proposal evolved from broader discussions within IETF HTTP working groups dating back to the late 1990s and early 2000s, particularly around extending core HTTP methods (GET, POST, PUT, DELETE) to better support distributed authoring and versioning protocols like WebDAV and DeltaV. These conversations highlighted the need for more granular resource manipulation without relying on ad-hoc extensions or overloading existing methods. Key motivations outlined in the early drafts included enabling efficient partial updates in scenarios such as WebDAV-based authoring for large files (e.g., image editing in tools like Adobe Photoshop), DeltaV versioning for incremental changes across multiple files, and lightweight configuration updates in the SIMPLE working group for presence and instant messaging systems. A central aim was to support non-idempotent partial modifications—allowing operations that might not be safely repeatable without altering the resource in unintended ways—while avoiding the resource creation side effects typical of POST requests. The draft received initial feedback through the IETF HTTP working group mailing list, focusing on issues like delta encoding formats, error responses for unsupported patches (e.g., 501 Not Implemented), and interoperability with caching mechanisms.[10] It underwent multiple iterations, including versions 01 through 06 in 2004, which refined semantics and incorporated references to existing delta standards like RFC 3229.[11] After a hiatus, the effort resumed in 2007 with James M. Snell as co-author in draft-07, introducing MIME-based media types for patch documents and addressing prior concerns about encoding flexibility.[12] Further revisions continued through 2009, culminating in draft-16 on November 25, 2009, which incorporated feedback on concurrency handling, status codes, and registry requirements.[13]Standardization Process
The PATCH method for HTTP was formally standardized in March 2010 through RFC 5789, published as a Proposed Standard by the Internet Engineering Task Force (IETF).[1] Authored by Lisa M. Dusseault and James M. Snell, the document defines PATCH as a method for applying partial modifications to resources, distinguishing it from full replacements via PUT, and specifies its non-safe and non-idempotent semantics as per HTTP/1.1.[14] In 2022, the PATCH method was integrated into the consolidated HTTP semantics specification in RFC 9110, which obsoleted earlier HTTP/1.1 documents and elevated HTTP to Internet Standard status (STD 97).[15] This update affirmed the core definition and usage of PATCH without introducing major changes, maintaining its role in enabling precise resource updates while emphasizing that its semantics depend on the request's media type.[16] Errata for RFC 5789 have been documented in the IETF datatracker, with a key verified technical erratum (ID 3169) providing clarification on media types.[17] This erratum specifies that servers should reject PATCH requests using media types without defined patch semantics—such as generic "application/xml" or "application/json"—with a 415 Unsupported Media Type response, ensuring predictable behavior.[17] The original RFC already addresses idempotency by stating that repeated identical PATCH requests may produce different results, unlike idempotent methods like PUT.[14] As of 2025, no significant updates to the PATCH specification have occurred since RFC 9110, reflecting its stability within the HTTP protocol family.[15] The method continues to be referenced in modern specifications, including HTTP/3 (RFC 9114), which inherits PATCH semantics from the shared HTTP architecture without alteration.[18]Comparisons with Other Methods
PATCH versus PUT
The HTTP PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.[19] In contrast, the PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the request URI, enabling partial modifications without requiring the full resource representation.[20] This semantic difference means PUT performs a complete replacement, treating the enclosed entity as the new version of the entire resource, whereas PATCH provides instructions for targeted alterations to the existing resource state.[20] Regarding idempotency, PUT is defined as idempotent, such that multiple identical requests have the same effect as a single request, with no additional side effects on the server state.[21] PATCH, however, is neither safe nor idempotent in general, as repeating the request may lead to different outcomes depending on the patch format and application (e.g., operations like incrementing a counter).[20] Idempotency for PATCH can be achieved through conditional requests, such as using the If-Match header with ETags, but it is not inherent to the method.[20] In terms of resource handling, PUT requires the client to have complete knowledge of the resource's current state to construct the full replacement, which can be inefficient for large or complex resources.[19] PATCH allows clients to send only the necessary changes, avoiding the need to resend unchanged portions and supporting formats like JSON Patch for precise updates.[20] For simple resources or scenarios requiring full synchronization, PUT is appropriate, as it ensures the resource matches the client's representation exactly; PATCH is preferable for complex or large resources where partial updates reduce bandwidth and minimize error risks from incomplete state knowledge.[19] Both methods impact caching and versioning similarly in core semantics: a successful PUT or PATCH response (2xx or 3xx status) requires caches to invalidate the effective request URI, as well as any URIs indicated by Location or Content-Location headers (if on the same host).[22]PATCH versus POST
The HTTP POST method is primarily intended for submitting data to be processed by the target resource according to its specific semantics, such as creating new resources, appending data to existing ones, or triggering server-side operations like form submissions.[23] Unlike other methods, POST is not idempotent, meaning that repeating the same request may result in different outcomes, such as multiple resource creations.[24] The target URI in a POST request identifies the resource responsible for processing the enclosed representation, but it does not necessarily correspond to the location of any newly created resource; instead, the server may assign and return a new URI via the Location header if creation occurs.[23] In contrast, the HTTP PATCH method is designed strictly for applying partial modifications to an existing resource identified by the request URI, using a patch document that specifies the changes in a standardized format.[25] This direct targeting of the resource URI ensures that PATCH operations modify the specified entity without creating new ones, providing clearer semantics for updates compared to POST.[26] PATCH promotes interoperability through defined media types for patch documents, whereas POST lacks a universal standard for such update operations, allowing varied and resource-specific processing.[25] Although POST can sometimes be used to mimic resource updates by processing submitted data to alter an existing entity, this approach lacks semantic precision and may lead to unintended side effects, such as accidental resource creation if the server's processing logic interprets the request that way.[23] PATCH mitigates these risks by explicitly signaling partial modification intent, avoiding the ambiguity inherent in POST's flexible semantics.[25] Historically, the broad applicability of POST for diverse operations, including ad-hoc updates, highlighted the need for a dedicated method to handle precise partial modifications, leading to the formalization of PATCH to improve consistency and reduce reliance on non-standard POST usages.[27]Mechanics of Patching
Applying Changes to Resources
The PATCH method enables clients to request partial modifications to a resource identified by the Request-URI by sending a patch document in the request entity body, which describes the set of changes to be applied.[4] This document specifies the modifications using a media type that indicates the format of the instructions, allowing the server to process them accordingly.[4] Upon receiving the request, the server interprets the patch document and applies the described changes to the existing resource, potentially creating a new resource if the target URI does not exist, depending on the semantics of the patch format and server policy.[4] Servers bear the responsibility of validating the patch document's format and ensuring its compatibility with the target resource before attempting to apply any changes.[4] If validation succeeds, the server processes the instructions to generate a new version of the resource; successful application typically results in a response containing the updated resource representation or a status indicating completion, along with relevant headers such as an updated ETag.[4] In cases of failure during application, the server must handle the issue without leaving the resource in a partially modified state, ensuring graceful recovery to maintain resource integrity.[4] The application of changes via PATCH is required to be atomic, meaning the server must apply the entire set of modifications or none at all, preventing any exposure of intermediate states to concurrent requests.[4] This atomicity ensures that operations remain reliable even in concurrent environments, though the RFC does not specify mechanisms for distributed transactions across multiple resources.[4] To manage concurrency and avoid overwriting unintended changes, clients should include conditional headers such as If-Match with a strong ETag in the PATCH request, which the server uses to verify that the resource has not been modified since the ETag was obtained.[4] If the precondition fails, the server rejects the request, allowing the client to reconcile conflicts before retrying.[4] This interaction with ETags supports optimistic concurrency control, enhancing the safety of partial updates in collaborative scenarios.Common Patch Document Formats
The HTTP PATCH method, as defined in RFC 5789, does not mandate a default media type for the request body, allowing flexibility for various patch document formats tailored to the resource's representation.[1] Instead, servers advertise supported media types via the Accept-Patch response header, which lists comma-separated media types such as application/example or text/example in hypothetical cases.[1] Clients must specify the appropriate Content-Type header in the PATCH request to indicate the format used.[1] One widely adopted format is JSON Merge Patch, standardized in RFC 7396 with the media type application/merge-patch+json.[2] This format represents modifications as a JSON object that mirrors the structure of the target JSON document, where keys indicate paths to update, new values replace existing ones, and null values signal deletions.[2] For nested objects, the merge recurses deeply, adding absent members and preserving unchanged ones; non-object patches replace the entire target.[2] An example patch to update a user profile might appear as:{
"name": "Updated Name",
"email": null,
"address": {
"city": "New City"
}
}
{
"name": "Updated Name",
"email": null,
"address": {
"city": "New City"
}
}
[
{"op": "replace", "path": "/name", "value": "Updated Name"},
{"op": "remove", "path": "/email"},
{"op": "add", "path": "/address/city", "value": "New City"}
]
[
{"op": "replace", "path": "/name", "value": "Updated Name"},
{"op": "remove", "path": "/email"},
{"op": "add", "path": "/address/city", "value": "New City"}
]
element containing sequential
<patch xmlns:p="urn:ietf:rfc:7351">
<p:add sel="/user/@status">active</p:add>
<p:replace sel="/user/email">[email protected]</p:replace>
<p:remove sel="/user/old-field"/>
</patch>
<patch xmlns:p="urn:ietf:rfc:7351">
<p:add sel="/user/@status">active</p:add>
<p:replace sel="/user/email">[email protected]</p:replace>
<p:remove sel="/user/old-field"/>
</patch>
Practical Examples
Basic HTTP PATCH Request
A basic HTTP PATCH request applies partial modifications to a specific resource identified by the Request-URI, using a patch document in the request body to describe the changes.[4] Unlike methods such as PUT, which replace the entire resource, PATCH enables targeted updates without resending the full resource representation.[4] The patch document's format is specified via theContent-Type header, allowing servers to parse and apply the instructions atomically—meaning either all changes succeed or none are applied.[4]
Consider a simple example where a client updates a single field in a user resource at /user/123. The request uses a basic text/plain format for the patch document. Note that there is no standardized format for text/plain patch documents; this is a simple illustrative example assuming server-specific parsing of key-value pairs like "name=John Doe" to modify the user's name. The request includes the If-Match header with an ETag for conditional application, ensuring the update only proceeds if the resource has not been modified concurrently.[4]
PATCH /user/123 HTTP/1.1
Host: example.com
Content-Type: text/plain
If-Match: "abc123"
Content-Length: 13
name=John Doe
PATCH /user/123 HTTP/1.1
Host: example.com
Content-Type: text/plain
If-Match: "abc123"
Content-Length: 13
name=John Doe
ETag header reflecting the new resource state.[4]
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "def456"
Content-Length: 55
{"id":123,"name":"John Doe","email":"[email protected]"}
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "def456"
Content-Length: 55
{"id":123,"name":"John Doe","email":"[email protected]"}
/user/123, to specify which entity to modify.[4] The server then parses the body according to the declared Content-Type, interpreting the text/plain content as instructions to update the indicated fields.[4] Finally, the server validates any preconditions (e.g., via If-Match), applies the changes if valid, and returns the appropriate response status.[4] This basic approach provides an introductory illustration, while more structured formats like JSON Patch offer advanced operations for complex scenarios.[4]
JSON Patch Example
JSON Patch, as specified in RFC 6902, uses a JSON array of operation objects to describe changes to a target JSON document.[3] Each operation includes an "op" member indicating the action (such as "add", "replace", or "remove"), a "path" member using JSON Pointer syntax from RFC 6901 to locate the target, and optionally a "value" member for the new data.[3][29] The media type for these documents is application/json-patch+json.[3] Consider a sample target resource at /resource/456, represented as the following JSON object:{
"name": "Original Name",
"tags": []
}
{
"name": "Original Name",
"tags": []
}
[
{"op": "replace", "path": "/name", "value": "New Name"},
{"op": "add", "path": "/tags", "value": ["new"]}
]
[
{"op": "replace", "path": "/name", "value": "New Name"},
{"op": "add", "path": "/tags", "value": ["new"]}
]
{
"name": "New Name",
"tags": ["new"]
}
{
"name": "New Name",
"tags": ["new"]
}
Advantages and Trade-offs
Benefits over Alternatives
The HTTP PATCH method offers significant efficiency advantages over alternatives like PUT by enabling partial updates to a resource, where only the modified portions are transmitted in the request body rather than the entire resource representation. This reduction in payload size minimizes bandwidth usage and decreases processing overhead on both client and server sides, particularly beneficial for large resources or high-latency networks. For instance, updating a single field in a voluminous JSON document via PATCH avoids the redundancy of resending unchanged data, as required by PUT, leading to faster request completion times.[1][6] PATCH provides semantic clarity by explicitly signaling the intent to perform a partial modification, distinguishing it from PUT (full replacement) or POST (creation or non-standard actions), which enhances API design and documentation practices. This clear delineation allows developers to define precise contracts for resource updates, reducing ambiguity in how endpoints should behave and making APIs more intuitive for consumers. In RESTful architectures, using PATCH for partial changes promotes consistent method usage, facilitating better tooling, testing, and maintenance.[1][30] The flexibility of PATCH stems from its support for diverse patch document formats and operation types, accommodating complex modifications beyond simple field replacements. Standardized formats like JSON Patch enable operations such as adding, removing, replacing, moving, copying, or testing values within a resource, applied sequentially to achieve atomic or multi-step updates. This adaptability suits varied data structures and application needs, such as reordering array elements or conditional validations, without relying on custom POST endpoints.[1][3]Potential Drawbacks
One significant drawback of the HTTP PATCH method is its lack of inherent idempotency, meaning that repeating the same PATCH request multiple times may result in different outcomes as changes can accumulate on the resource.[1] Unlike PUT, which replaces the entire resource and thus remains unchanged upon repetition, PATCH requires developers to design requests carefully, often using conditional headers like If-Match with ETags to achieve idempotent behavior and avoid unintended modifications.[1] This non-idempotent nature can complicate retry logic in distributed systems, potentially leading to data inconsistencies if network failures occur during application.[31] Server implementations of PATCH exhibit variability due to the absence of uniform rules for applying patch documents, resulting in inconsistent behavior across different services.[1] The method supports multiple patch formats without a default, such as JSON Patch or custom media types advertised via the Accept-Patch response header, which demands that clients and servers negotiate compatible formats explicitly.[1] This flexibility, while enabling diverse use cases, often leads to interoperability issues, as servers must process changes atomically but may interpret partial updates differently based on their specific logic.[1] The complexity of structured patch formats like JSON Patch further exacerbates implementation challenges compared to simpler methods such as PUT.[3] JSON Patch requires parsing and sequentially applying a series of operations (e.g., add, replace, remove) using JSON Pointers to target specific paths, which introduces additional client-side and server-side logic for validation and error handling.[3] A failure in any single operation halts the entire patch, demanding robust testing to ensure sequential integrity, unlike the straightforward full replacement of PUT.[3] Adoption barriers persist for PATCH, particularly in legacy systems, as the method was only standardized in 2010 and remains optional in some older web servers and frameworks.[1] Prior to this, PATCH was not universally supported, and even as of 2025, environments running outdated software—such as pre-2012 versions of Apache HTTP Server or certain embedded systems—may lack native handling, forcing developers to fall back to POST or PUT for partial updates.[31] This uneven support hinders seamless integration in heterogeneous infrastructures.[31]Implementation Considerations
Server-Side Handling
When processing an HTTP PATCH request, servers must first parse the request body, which contains a patch document specifying partial modifications to the target resource. The server verifies the Content-Type header to ensure the document uses a supported media type, such as application/json-patch+json for JSON Patch operations. If the document is malformed or syntactically invalid, the server responds with a 400 Bad Request status code. For unsupported media types, it returns 415 Unsupported Media Type and should include an Accept-Patch response header listing the supported formats to guide clients.[4] Validation extends to semantic checks, ensuring the proposed changes are applicable to the resource's current state. Servers should evaluate preconditions, such as the If-Match header with an ETag value, to confirm the resource has not been modified concurrently; failure triggers a 412 Precondition Failed response, promoting idempotency and preventing lost updates. The changes are then applied atomically—either all succeed or none do—to maintain resource consistency, though the method may produce side effects on related resources.[4] Upon successful application, servers typically respond with 200 OK, including the full updated resource representation in the body to allow clients to verify the outcome, or 204 No Content if no body is needed. Error conditions, such as resource conflicts yielding 409 Conflict, ensure reliable handling without partial updates.[4] Best practices include advertising PATCH support via the Accept-Patch header in OPTIONS responses, enabling clients to query compatible formats proactively. Servers should log patch operations, including the original and updated resource states, timestamps, and actor identifiers, to facilitate auditing and compliance with security policies. This logging aids in tracking modifications without altering the core protocol semantics.[32] The PATCH method integrates seamlessly with HTTP/1.1, HTTP/2, and HTTP/3, as it relies on standard request-response semantics without version-specific adaptations; multiplexing in HTTP/2 and QUIC transport in HTTP/3 enhance performance for concurrent PATCH operations but require no additional server logic.[33]Client-Side Usage
Clients construct HTTP PATCH requests by specifying the target resource's URI in the request line, selecting an appropriate patch document format such as JSON Patch or JSON Merge Patch, and including the patch operations in the request body. The Content-Type header must indicate the chosen format, for example, application/json-patch+json for JSON Patch documents, while the PATCH method ensures partial updates without replacing the entire resource. To support conditional requests and prevent overwrites, clients often include headers like If-Match with an ETag value to verify the resource's current state, or If-None-Match to apply the patch only if the resource has changed since last accessed. For robustness, clients implement fallback strategies by first probing the server's capabilities using an OPTIONS request to the resource URI, checking the Accept-Patch response header for supported media types; if PATCH is unsupported or the desired format is absent, the client reverts to a PUT request for full resource replacement. This probing aligns with HTTP's extensibility model, allowing graceful degradation in heterogeneous environments. In popular libraries, client-side PATCH usage simplifies construction and handles asynchronous responses. For instance, in JavaScript with Axios, a PATCH request is sent via axios.patch('/resource/1', { op: 'replace', path: '/name', value: 'New Name' }, { headers: { 'If-Match': etag } }), which returns a Promise resolving to the server's response or error. Similarly, in Python's requests library, clients use requests.patch('https://api.example.com/resource/1', json=[{"op": "replace", "path": "/name", "value": "New Name"}], headers={'If-Match': etag}), managing sessions for authentication and retries on transient failures. These frameworks abstract low-level details like header serialization while supporting async patterns for non-blocking operations. Testing PATCH requests typically involves command-line tools like curl to simulate client behavior and verify outcomes. A basic curl command might be curl -X PATCH -H "Content-Type: application/json-patch+json" -H "If-Match: "abc123"" -d '[{"op":"replace","path":"/name","value":"Updated"}]' https://api.example.com/resource/1, expecting a 2xx status for success or 4xx/5xx for issues like conflicts. Clients monitor responses for status codes, ensuring 200 OK or 204 No Content indicates successful partial application, while logging headers like ETag in the response for subsequent conditional requests.Error Handling
Malformed Patch Documents
A malformed patch document in an HTTP PATCH request refers to a body that fails to parse correctly due to invalid syntax or structural errors, such as non-compliant JSON in a JSON Patch document or incorrect formatting of operations.[34] According to RFC 5789, this occurs when the server cannot interpret the provided patch document as properly formatted, preventing any partial application of changes.[34] When encountering a malformed patch document, servers should respond with a 400 Bad Request status code, as recommended in RFC 5789, and include descriptive error details in the response body where feasible to aid client debugging.[34] This status indicates that the request is syntactically invalid, ensuring no modifications are attempted on the target resource. For JSON Patch specifically, RFC 6902 mandates that evaluation of the document terminates immediately upon detecting a violation of normative requirements, rendering the entire patch unsuccessful without proceeding further.[3] Servers are advised to reject malformed documents early in processing to avoid unintended side effects, validating the body against the expected format (e.g., JSON syntax or operation structure) before any resource interaction.[34] Clients, upon receiving a 400 response, should correct the syntax or structure issues in the patch document and retry the request, potentially using tools like JSON validators to ensure compliance.[3] Common examples include syntax errors in JSON Patch, such as invalid JSON Pointer paths that do not conform to RFC 6901 (e.g., a path like "/users/0/name~" missing proper tilde escaping for special characters) or operations with duplicate "op" members (e.g., specifying both "add" and "remove" in the same object).[3] Another case is a malformed array of operations where an entry lacks required fields like "path" or "value," causing parsing to fail. For instance:[
{
"op": "replace",
"path": /invalid, // Invalid JSON Pointer syntax
"value": "new value"
}
]
[
{
"op": "replace",
"path": /invalid, // Invalid JSON Pointer syntax
"value": "new value"
}
]
Unsupported Patch Formats
When a client submits an HTTP PATCH request with a patch document whose media type is not supported by the server, the server rejects the request due to the inability to process the specified format. This occurs when the Content-Type header in the request does not match any of the media types advertised by the server in its Accept-Patch response header, such as a custom or non-standard patch format that the server does not recognize.[1] In response, the server returns a 415 Unsupported Media Type status code to indicate that the payload format is unacceptable. To assist the client, the server should include an Accept-Patch header in the 415 response, listing the supported media types (e.g., application/json or application/merge-patch+json) as alternatives for retrying the operation.[35] To prevent such errors, clients are recommended to first send an OPTIONS request to the target resource to retrieve the server's Accept-Patch header and confirm supported formats before issuing the PATCH. Servers, in turn, must clearly advertise their capabilities via this header in OPTIONS responses, ensuring transparency about acceptable patch document media types.[36] This mismatch in format support has significant implications for API interactions, as it prohibits partial resource updates via PATCH and may compel clients to fall back to full resource replacement methods like PUT, potentially increasing bandwidth usage and risking overwrites of unchanged data.[1]Unprocessable Requests
In HTTP PATCH requests, unprocessable requests occur when the patch document is syntactically valid and the server understands its content type, but the proposed changes cannot be applied due to semantic invalidity specific to the resource, such as attempting to modify an immutable field or introducing a type mismatch that violates the resource's schema.[37][35] This scenario is an extension of concepts from WebDAV protocols, where instructions are well-formed but semantically erroneous, rendering them inapplicable without altering the resource's integrity.[38] The standard HTTP response for such cases is the 422 Unprocessable Entity status code, which signals that the server recognizes the request's structure but deems the content unprocessable.[37] The response body should include detailed error information to aid client correction, such as descriptions of the invalid operations or affected fields, often in a format like JSON with error codes and messages.[35] For instance, if a PATCH attempts to set a read-only property like a resource's creation timestamp, the server returns 422 with an explanation like{"error": "Cannot modify immutable field: created_at"}.[35]
Representative examples include trying to append an item to a non-extensible array defined in the resource's schema, which would violate structural constraints, or submitting a string value for a numeric field, triggering a type mismatch error.[35] Another case arises when the patch violates application-specific business rules, such as updating a user's age to a negative value in a system enforcing positive integers only.[37]
This differs from a 400 Bad Request response, which addresses syntactic malformations in the request itself, whereas 422 specifically denotes valid syntax coupled with unapplyable logic due to resource semantics.[37] As noted in malformed patch document handling, 422 applies only after syntax validation succeeds.[35]