HTTP PUT vs HTTP PATCH in .NET Web API: Which Method to Use for Updating Resources?

HTTP methods are an essential part of the Hypertext Transfer Protocol (HTTP), which is the primary protocol used for communication between web servers and web clients. There are several HTTP methods, also known as HTTP verbs, that are used to communicate with web servers and perform actions on resources.

The most important or commonly used HTTP methods are as below:

  1. GET – retrieves a representation of the resource identified by the URL. This method is used for reading data from the server.
  2. POST – submits an entity to be processed by the server. This method is commonly used for creating new resources or submitting data to the server for processing.
  3. PUT – replaces the current representation of the resource with the entity sent in the request. This method is used for updating an existing resource.
  4. PATCH – partially updates the current representation of the resource with the entity sent in the request. This method is used when updating part of a resource.
  5. DELETE – deletes the resource identified by the URL. This method is used for deleting resources from the server

You can see that both PUT (HttpPut) and PATCH (HttpPatch) are used for updating resources, but what are the key diferences between these two and which method should you use for updating resources.

HTTP PUT

HTTP PUT is used to update an existing resource with a new representation of the entire resource. The entire representation of the resource is sent in the request body, which is used to replace the existing representation of the resource on the server.

Example:

Let’s say you have a User entity in your application and you want to update the data of a user in your app. For that, you would need to send an HttpPut request to the server. An example CURL representation of the request would look like below:

curl -X PUT -H "Content-Type: application/json" -d '{
    "name": "Ervis Trupja",
    "email": "[email protected]",
    "age": 30
}' https://dotnethow.net/api/users/1

The curl command uses the -X option to specify the HTTP method as PUT. The -H option is used to set the Content-Type header to application/json. The -d option is used to set the data payload for the request, which is a JSON object containing the user’s information. Finally, the URL for the API endpoint is specified at the end of the command.

The API to handle this request would look like below:

[HttpPut("{id}")]
public IActionResult UpdateUser(int id, [FromBody] UserDto userDto)
{
    var user = _userService.GetUserById(id);

    if (user == null)
    {
        return NotFound();
    }

    // Update the user's information
    user.Name = userDto.Name;
    user.Email = userDto.Email;
    user.Age = userDto.Age;

    _userService.UpdateUser(user);

    return Ok(user);
}

where UserDto class looks like below:

public class UserDto
{
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

now let’s have a look at an example about PATCH usage.

HTTP PATCH

HTTP PATCH, on the other hand, is used to update part of an existing resource. Unlike PUT, only the changes to the resource are sent in the request body, not the entire representation of the resource.

Let’s say that you want to updat only the Email of the user, so instead of sending the whole object in an HttpPut request, you could use an HttpPatch request to only send the Email value instead.

An example CURL representation of the request would look like below:

curl -X PATCH -H "Content-Type: application/json-patch+json" -d '[
    {
        "op": "replace",
        "path": "/email",
        "value": "[email protected]"
    }
]' https://dotnethow.net/api/users/1 

The curl command uses the -X option to specify the HTTP method as PATCH. The -H option is used to set the Content-Type header to application/json-patch+json, which is the MIME type for JSON Patch requests. The -d option is used to set the data payload for the request, which is a JSON Patch operation that replaces the user’s email address with a new one. Finally, the URL for the API endpoint is specified at the end of the command.

The API to handle this request would look like below:

[HttpPatch("{id}")]
public IActionResult UpdateUserEmail(int id, [FromBody] JsonPatchDocument<UserDto> patch)
{
    var user = _userService.GetUserById(id);

    if (user == null)
    {
        return NotFound();
    }

    var userDto = _mapper.Map<UserDto>(user);

    // Apply the patch to the user DTO
    patch.ApplyTo(userDto);

    // Update the user's email in the database
    user.Email = userDto.Email;

    _userService.UpdateUser(user);

    return Ok(user);
}

The [FromBody] attribute specifies that the JsonPatchDocument<UserDto> parameter should be deserialized from the HTTP request body. This parameter contains the JSON Patch operations that will be applied to the UserDto object.
The _mapper.Map<UserDto>(user) method is used to map the User object retrieved from the data store to a UserDto object. This is done to provide a simpler representation of the user to the client that may not need all the details of the user.

The patch.ApplyTo(userDto) method is called to apply the JSON Patch operations to the UserDto object.

Summary

In summary, HTTP PUT is used to update the entire representation of a resource, while HTTP PATCH is used to update part of a resource. Both methods are useful for updating resources on the server, depending on the specific use case.

Image by mamewmy on Freepik


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.