Junior — Middle
What is the primary purpose of the PATCH method in REST API for updating resources?
sobes.tech AI
Answer from AI
The PATCH method in REST API is used for partial updates of a resource. Unlike PUT, which usually replaces the entire resource, PATCH allows sending only the fields that need to be changed, leaving the rest unchanged. This saves traffic and simplifies updates when only part of the data needs to be modified.
Example of using PATCH in C# with ASP.NET Core:
[HttpPatch("users/{id}")]
public IActionResult PatchUser(int id, [FromBody] JsonPatchDocument<User> patchDoc)
{
var user = _userRepository.GetById(id);
if (user == null) return NotFound();
patchDoc.ApplyTo(user, ModelState);
if (!ModelState.IsValid) return BadRequest(ModelState);
_userRepository.Update(user);
return NoContent();
}
Here, JsonPatchDocument contains instructions for modifying specific fields of the User object.