Home » C# » How to do a partial update in Net Core API

How to do a partial update in Net Core API

By Emily

If you’re building a Net Core API you’ll need to write some GET endpoints, that retrieve data from the database, and some POST endpoints, which add new data to the database. Updates can be a little more complicated. Do you want to have to send the whole object each time one of the properties is updated? Or do you want to do a partial update and only send the properties which have changed? In this case, I wanted to send only the properties which had changed, and this post explains how to do that using PATCH. In my project we are using Entity Framework and the repository pattern, so my examples are based around that approach.

What is PATCH?

The PATCH request method was introduced in 2010. Prior to that if you wanted to update an entity using an API you would use the PUT request method, which required that you needed to send the whole entity in every request. Take this object as an example:

 {
   "id":1,
   "title":"Backpack",
   "price":109.95,
   "description":"Your perfect pack for everyday use",
   "category":"Accessories",
   "image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
   "rating":{
      "rate":3.9,
      "count":120
   }
}

In order to update the title only, if we had to use PUT, we would have to send the whole object like this:

 {
   "id":1,
   "title":"Lightweight Backpack",
   "price":109.95,
   "description":"Your perfect pack for everyday use",
   "category":"Accessories",
   "image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
   "rating":{
      "rate":3.9,
      "count":120
   }
}

But we really want to do is to only send the properties which have changed, like this:

 {
   "title":"Lightweight Backpack" 
 }

And that is what PATCH enables us to do – although you can’t do it quite like that, there are some techniques you need, so read on.

How to use PATCH to do a partial update

We have to use a JSONPatchDocument to do this. First of all you’ll need to install the Microsoft.AspNetCore.JsonPatch Nuget package. Then you need to create the PATCH request body, which in this specific example would be like this:

[
  { "op": "replace", "path": "/title", "value": "Lightweight Backpack" }
]

This is an example of doing an Update using JSONPatchDocument.

JSONPatchDocument update (replace) example

Now let’s look at the code that we’ll need to send this PATCH request in C#.

[HttpPatch("{productId}")]
public IActionResult UpdateProduct(int productId, [FromBody] JsonPatchDocument<Product> patchDoc)
{
  try
  {
    	//You will need to edit this line to work with your code base. 
    	//_unitOfWork is my generic repository. You may need to change this to your
    	//context name, or a different repository name.
    	Product product = _unitOfWork.Product.GetById(productId);
    	patchDoc.ApplyTo(product, ModelState);

        if (!ModelState.IsValid)
        {
          return BadRequest(ModelState);
        }
		
		_unitOfWork.Product.Update(product);
        _unitOfWork.Save();

    	return new ObjectResult(product);
  }
  catch (Exception ex)
  {
    _logger.LogError($"Something went wrong inside the UpdateProduct action: {ex}");
    return StatusCode(500, ex);
  }
}

If the update works then you will see the full product returned in JSON, with the updated values.

Summary

This is a full example of how to do a partial entity update in a Net Core REST API with Entity Framework.

Related: