restpatch

API examples using JSON PATCH for partial updates


I'm looking for the best solution to apply a partial update to an object with a REST API (ASP.NET)

I originally wanted to use "JSON Merge Patch" format (rfc7396), but I was not able to do it with ASP.NET (hard to differentiate ignored fields, and fields set to null)

I tried to use PATCH with JSON PATCH format and it is working.

Ex. :

[
    { "op": "replace", "path": "/Name", "value": "patchedValue" },
    { "op": "replace", "path": "/EnumTest", "value": "blo" },
    { "op": "replace", "path": "/SubItem/Name", "value": "patchedValue" }
]

I see that Microsoft support this format (asp.net core json patch), but I have no idea if this format is often used. I don't want to be the only one using it... I'm looking for API from big companies that is using this format for partial update. Do you have some examples ?


Solution

  • As I couldn't differentiate properties that I wanted to set to NULL and ignored properties, and I wanted a simple request for the person using the API, my workaround was :

    1. Manually read the request JSON instead of deserializing it

      person.JsonObject = await Request.Content.ReadJsonAsync();
      
    2. Make my model inherit from this class

       public class RequestBase
       {
         internal JObject JsonObject { get; set; }
      
         internal bool IsJsonPropertySet(string propertyPath)
         {
           if (JsonObject == null)
               return true; // if null => full update.
      
           return JsonObject.SelectToken(propertyPath) != null;
         }
       }
      
    3. For each property, manually check if it is set in the JSON and update the value

      if (src.IsJsonPropertySet("validity.startDate"))
         dest.ValidityStartDate = src.Validity.StartDate;
      

    I'm sure there is a way better solution, but I didn't find it for my old Web API project...

    It is working fine, but when the API client code is generated from the swagger in a C# project, the PATCH methods can't easily be used.