USE Patch action to update a single resource
When updating a single resource in a RESTful API, it is generally recommended to use the PATCH method rather than the PUT method. Unlike PUT, which completely replaces the resource with the new data sent in the request payload, PATCH allows you to update specific fields of the resource without affecting other fields.
Using the PATCH method to update a single resource can be particularly useful in situations where you only need to update a few fields of the resource, or when you want to avoid sending unnecessary data over the network. For example, if you have a user profile resource with multiple fields such as name, email, and address, you could use PATCH to update just the email address without affecting the other fields.
ASP.NET JsonPatch is a library for applying JSON patch documents to objects in a .NET application. It provides a simple and intuitive way to apply changes to objects using the PATCH HTTP method in a RESTful API.
JsonPatch is particularly useful for updating objects that have a large number of properties, as it allows you to send only the changes that need to be made to the server, rather than sending the entire object. This can help to reduce the amount of data that needs to be sent over the network, which can improve the performance of your application.
JsonPatch supports the JSON Patch and JSON Merge Patch formats, which are both widely used in the RESTful API community. It provides a fluent API for building patch documents, which can be applied to objects using the ApplyTo method.
While code block below seems very simple, there are a few constraints needs to be followed while developing a patch endpoint. Let's follow what's been done in this example from a UsersController:
- Name your method as PatchUser
- Return a single object with type matching method name as in PatchUserResponse
- Get id from route that's defined in [HttpPatch("{id}")]
- Get request payload from body with a parameter typed JsonPatchDocument<PatchUserRequest>
- Place appropriate ProducesResponseType attributes for each return type
- Return 404 if resource not found at given location
- Return 200 if update operation is successfull
- Return ProblemDetails for errors
[HttpPatch("{id}")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PatchUserResponse))]
public async Task<IActionResult> PatchUser([FromRoute] long id, [FromBody] JsonPatchDocument<PatchUserRequest> request)
{
PatchUserResponse response = new PatchUserResponse();
return Ok(response);
}
Never implement custom methods other than described 6 actions (Query, Get, Create, Update, Patch, Delete).