Partial update your .NET Core HTTP API resources

Partial update your .NET Core HTTP API resources

Today, I was struggling with the idea of so-called partial updates. Imagine the following scenario, which is actually a quite common one. You’d like to update some resource in your HTTP API, for example, the product object. However, such entity may contain a lot of properties, tens or even hundreds, and you want to change only its name or a few more things as well (doesn’t really matter). And that’s where JSON Patch comes in really handy.


 

If you were to use the typical PUT request, you’d probably have to send the whole object including all of its properties, which might result in unnecessary bandwidth usage amongst other things, such as possible mistakes (e.g. missing fields etc.). You could also expose the POST endpoints for the atomic operations such as /products/1/name that would be responsible for updating a single property, yet again – multiple updates, multiple calls, not to mention the backend mess caused by implementing so many different operations.

And the solution for all of this is JSON Patch – similarly to the GraphQL, you are free to include only these properties that you want to update. For our product entity, such HTTP PATCH request could look like this:

As you can see, by following the RFC 6902 standard, you can easily define what should be done with your resource, and you have multiple operations to choose from e.g. “add” or “replace” – you can find the whole description along with the examples in one of the links above.

Finally, there are already working implementations of the JSON Patch for the ASP.NET Core and there’s also another one that supports Nancy (I’ve just started using it and can verify that it does work as expected). Since I really like the command & event handlers pattern and have been working with distributed systems recently, e.g. in our Collectively platform I found it really helpful, as I can almost directly map the incoming request to some particular update command that is getting pushed to the service bus automatically, and I don’t need to do any additional properties checking or assigning at all.

You can find the actual source code here. Also, make sure you check the following article, as it explains why PATCH really makes sense.

3 Comments Partial update your .NET Core HTTP API resources

  1. Pingback: Dew Drop - October 6, 2017 (#2576) - Morning Dew

  2. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #2438

Leave A Comment

Your email address will not be published. Required fields are marked *