USE Update action to update a single resource
HTTP PUT is an HTTP method used to update or replace an existing resource in a RESTful API. When a client sends a PUT request to an API endpoint, the API will update the resource identified by the request URI with the payload data sent in the request body. This payload data typically includes the updated attributes of the resource.
One of the key features of HTTP PUT is that it replaces the entire resource with the new data sent in the request payload. This means that any fields that are not included in the payload will be set to null or default values. This can be a disadvantage in situations where a partial update of the resource is needed, in which case the PATCH method should be used instead.
When using HTTP PUT, it is important to ensure that the request payload includes all of the required data for the resource being updated, and that any relevant validation is performed on the data before it is saved to the database. In addition, the API should return a response that includes the updated resource or a message indicating that the update was successful.
While code block below seems very simple, there are a few constraints needs to be followed while developing an update endpoint. Let's follow what's been done in this example from a UsersController:
- Name your method as UpdateUser
- Return a single object with type matching method name as in UpdateUserResponse
- Get id from route that's defined in [HttpPut("{id}")]
- Get request payload from body with a parameter typed UpdateUserRequest
- Place appropriate ProducesResponseType attributes for each return type
- Don't return 404 from Update endpoint since HttpPut endpoint should create this resource at given location if it does not exists
- Return 200 if update operation is successfull, 201 if resource is created
- Return ProblemDetails for errors
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UpdateUserResponse))]
public async Task<IActionResult> UpdateUser([FromRoute] long id, [FromBody] UpdateUserRequest request)
{
UpdateUserResponse response = new UpdateUserResponse();
return Ok(response);
}
Never implement custom methods other than described 6 actions (Query, Get, Create, Update, Patch, Delete).