wasAsked.

difference between PUT vs PATCH with example used in project

PwC · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

PUT - Replaces the entire resource with the representation sent by the client. - Fields omitted from the request are typically reset (to defaults or null) — the client must send the complete resource. - Idempotent: sending the same PUT request multiple times leaves the resource in the same state. - Can also create a resource at a client-specified URI in some APIs. PUT /api/users/42 { "name": "Asha Rao", "email": "asha@example.com", "phone": "9876543210", "city": "Pune" } PATCH - Applies a partial modification: only the specified fields change. - Smaller payloads, and less risk of overwriting changes made by others to fields you did not touch. - Not guaranteed to be idempotent: "set city to Pune" is idempotent, but "add 1 to loginCount" is not. PATCH /api/users/42 { "city": "Mumbai" } Common PATCH formats - JSON Merge Patch (RFC 7386, Content-Type: application/merge-patch+json): send only the changed fields; null means "remove or set to null". - JSON Patch (RFC 6902, Content-Type: application/json-patch+json): a list of operations: [ { "op": "replace", "path": "/city", "value": "Mumbai" }, { "op": "remove", "path": "/phone" } ] In ASP.NET Core, JsonPatchDocument<T> supports this (System.Text.Json support was added in .NET 10; earlier versions used Newtonsoft.Json). Example from a project (adapt to your own) "In our profile service, the mobile app updates only a user's notification preferences, so we exposed PATCH /api/users/me/preferences with merge-patch semantics. This avoided sending the full profile and prevented one device from overwriting changes made on another. For admin screens that edit the whole product record, we used PUT /api/products/{id} with the complete object and an ETag in an If-Match header for optimistic concurrency." Implementation notes - Validate the result after applying a patch, and apply patches to a DTO, not directly to the entity, to prevent over-posting. - Restrict which fields can be patched. - Use ETags or row versions to detect conflicting updates for both PUT and PATCH. - Return 200 with the updated resource or 204 No Content; 404 if the resource does not exist; 409 or 412 for conflicts. Summary: PUT means "here is the full new version"; PATCH means "change only these parts."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics