Web API 2 - Implementing a PATCH

I wanted to achieve exactly the same thing, but used a different method to others described here. I've created a working repo using this if you want to check it out:

https://github.com/emab/patch-example

If you have the following two models:

Database model

public class WeatherDBModel
    {
        [Key]
        public int Id { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public double Temperature { get; set; }
        public double WindSpeed { get; set; }
        public double Rain { get; set; }

        public Weather(int id, string city, string country, double temperature, double windSpeed, double rain)
        {
            Id = id;
            City = city;
            Country = country;
            Temperature = temperature;
            WindSpeed = windSpeed;
            Rain = rain;
        }
    }

Update model

Containing exact names of database model properties. Includes properties which can be updated

public class WeatherUpdateModel
{
      public string? City { get; set; }
      public string? Country { get; set; }
      public double Temperature { get; set; }
      public double WindSpeed { get; set; }
      public double Rain { get; set; }
}

This update model is sent to the service layer along with the id of the object you'd like to update.

You can then implement the following method in your repository layer which maps any non-null values from the updateModel into an existing entity if it has been found:

public Weather Update(int id, WeatherUpdate updateObject)
{
    // find existing entity
    var existingEntity = _context.Weather.Find(id);
    
    // handle not found
    if (existingEntity == null)
    {
        throw new EntityNotFoundException(id);
    }

    // iterate through all of the properties of the update object
    // in this example it includes all properties apart from `id`
    foreach (PropertyInfo prop in updateObject.GetType().GetProperties())
    {
        // check if the property has been set in the updateObject
        // if it is null we ignore it. If you want to allow null values to be set, you could add a flag to the update object to allow specific nulls
        if (prop.GetValue(updateObject) != null)
        {
            // if it has been set update the existing entity value
            existingEntity.GetType().GetProperty(prop.Name)?.SetValue(existingEntity, prop.GetValue(updateObject));               
        }
    }
    _context.SaveChanges();
    return existingEntity;
}

Using this method you can change your models without worrying about the update logic, as long as you ensure that the UpdateModel is kept up-to-date with the database model.


I hope this helps using Microsoft JsonPatchDocument:

.Net Core 2.1 Patch Action into a Controller:

[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody]JsonPatchDocument<Node> value)
{
    try
    {
        //nodes collection is an in memory list of nodes for this example
        var result = nodes.FirstOrDefault(n => n.Id == id);
        if (result == null)
        {
            return BadRequest();
        }    
        value.ApplyTo(result, ModelState);//result gets the values from the patch request
        return NoContent();
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, ex);
    }
}

Node Model class:

[DataContract(Name ="Node")]
public class Node
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "node_id")]
    public int Node_id { get; set; }

    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "full_name")]
    public string Full_name { get; set; }
}

A valid Patch JSon to update just the "full_name" and the "node_id" properties will be an array of operations like:

[
  { "op": "replace", "path": "full_name", "value": "NewNameWithPatch"},
  { "op": "replace", "path": "node_id", "value": 10}
]

As you can see "op" is the operation you would like to perform, the most common one is "replace" which will just set the existing value of that property for the new one, but there are others:

[
  { "op": "test", "path": "property_name", "value": "value" },
  { "op": "remove", "path": "property_name" },
  { "op": "add", "path": "property_name", "value": [ "value1", "value2" ] },
  { "op": "replace", "path": "property_name", "value": 12 },
  { "op": "move", "from": "property_name", "path": "other_property_name" },
  { "op": "copy", "from": "property_name", "path": "other_property_name" }
]

Here is an extensions method I built based on the Patch ("replace") specification in C# using reflection that you can use to serialize any object to perform a Patch ("replace") operation, you can also pass the desired Encoding and it will return the HttpContent (StringContent) ready to be sent to httpClient.PatchAsync(endPoint, httpContent):

public static StringContent ToPatchJsonContent(this object node, Encoding enc = null)
{
    List<PatchObject> patchObjectsCollection = new List<PatchObject>();

    foreach (var prop in node.GetType().GetProperties())
    {
        var patch = new PatchObject{ Op = "replace", Path = prop.Name , Value = prop.GetValue(node) };
        patchObjectsCollection.Add(patch);                
    }

    MemoryStream payloadStream = new MemoryStream();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(patchObjectsCollection.GetType());
    serializer.WriteObject(payloadStream, patchObjectsCollection);
    Encoding encoding = enc ?? Encoding.UTF8;
    var content = new StringContent(Encoding.UTF8.GetString(payloadStream.ToArray()), encoding, "application/json");

    return content;
}

}

Noticed that tt also uses this class I created to serialize the PatchObject using DataContractJsonSerializer:

[DataContract(Name = "PatchObject")]
class PatchObject
{
    [DataMember(Name = "op")]
    public string Op { get; set; }
    [DataMember(Name = "path")]
    public string Path { get; set; }
    [DataMember(Name = "value")]
    public object Value { get; set; }
}

A C# example of how to use the extension method and invoking the Patch request using HttpClient:

    var nodeToPatch = new { Name = "TestPatch", Private = true };//You can use anonymous type
    HttpContent content = nodeToPatch.ToPatchJsonContent();//Invoke the extension method to serialize the object

    HttpClient httpClient = new HttpClient();
    string endPoint = "https://localhost:44320/api/nodes/1";
    var response = httpClient.PatchAsync(endPoint, content).Result;

Thanks


@Tipx's answer re using PATCH is spot on, but as you've probably already found, actually achieving that in a statically typed language like C# is a non-trivial exercise.

In the case where you're using a PATCH to represent a set of partial updates for a single domain entity (e.g. to update the first name and last name only for a contact with many more properties) you need to do something along the lines of looping each instruction in the 'PATCH' request and then applying that instruction to an instance of your class.

Applying an individual instruction will then comprise of

  • Finding the property of the instance that matches the name in the instruction, or handling property names you weren't expecting
  • For an update: Trying to parse the value submitted in the patch into the instance property and handling the error if e.g. the instance property is a bool but the patch instruction contains a date
  • Deciding what to do with Add instructions as you can't add new properties to a statically typed C# class. One approach is to say that Add means "set the value of the instance's property only if property's existing value is null"

For Web API 2 on the full .NET Framework the JSONPatch github project looks to make a stab at providing this code, although it doesn't look like there's been a lot of development on that repo recently and the readme does state:

This is still very much an early project, don't use it in production yet unless you understand the source and don't mind fixing a few bugs ;)

Things are simpler on .NET Core as that has a set of functionality to support this in the Microsoft.AspNetCore.JsonPatch namespace.

The rather useful jsonpatch.com site also lists out a few more options for Patch in .NET:

  • Asp.Net Core JsonPatch (Microsoft official implementation)
  • Ramone (a framework for consuming REST services, includes a JSON Patch implementation)
  • JsonPatch (Adds JSON Patch support to ASP.NET Web API)
  • Starcounter (In-memory Application Engine, uses JSON Patch with OT for client-server sync)
  • Nancy.JsonPatch (Adds JSON Patch support to NancyFX)
  • Manatee.Json (JSON-everything, including JSON Patch)

I need to add this functionality to an existing Web API 2 project of ours, so I'll update this answer if I find anything else that's useful while doing that.


PATCH operations aren't usually defined using the same model as the POST or PUT operations exactly for that reason: How do you differentiate between a null, and a don't change. From the IETF:

With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

You can look here for their PATCH suggestion, but sumarilly is:

[
    { "op": "test", "path": "/a/b/c", "value": "foo" },
    { "op": "remove", "path": "/a/b/c" },
    { "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
    { "op": "replace", "path": "/a/b/c", "value": 42 },
    { "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
    { "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]