Skip to main content

How to do partial update for HTTP APIs in ASP.NET CORE MVC with JSON Patch



JSON Patch is a format for describing changes to a JSON document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the HTTP PATCH method, it allows partial updates for HTTP APIs in a standards compliant way. A JSON Patch document is just a JSON file containing an array of patch operations. The patch operations supported by JSON Patch are “add”, “remove”, “replace”, “move”, “copy” and “test”. The operations are applied in order: if any of them fail then the whole patch operation should abort.

The JSON Patch supports the following operations:

  • Add - Adds a value to an object or inserts it into an array.

  • Remove -  Removes a value from an object or array.
  • Replace - Replaces a value. Equivalent to a “remove” followed by an “add”.
  • Copy - Copy a value from one location to another within the JSON document. Both from and path are JSON Pointers.
  • Move - Move a value from one location to the other. Both from and path are JSON Pointers.
  • Test - Tests that the specified value is set in the document. If the test fails then the patch as a whole should not apply.

In earlier version of ASP.NET,  we need to use other third party libraries in order to achieve JSON patch, but the good thing is, ASP.NET Core supports this feature right out the box without the need to install any third party library.


Performing Partial Updating in ASP.NET Core
There are two main approach to perform patch operation. Listed below are the two ways:
  1. Sending JsonPatchDocument object as a parameter
  2. Creating JsonPatchDocument at runtime

For a start we need to add a reference to Microsoft.AspNet.JsonPatch in project.json.

"dependencies": {
   "Microsoft.AspNet.JsonPatch": "1.0.0-rc1-final",
},

In this article we will be using the first approach, and this involves the method accepting parameter of JsonPatchDocument from request body.

To illustrate further, we shall be adding a class, that will hold our data member.

public class Librarys
{
   public string Author { get; set; }
   public string Book { get; set; }
  
}


To move further, we will create HTTP API, that will accept JsonPatchDocument as a parameter from the request body.



[Route("api/[controller]")]
public class LibrarysController : Controller
{
   private Librarys librarys = new Librarys
   {
       Author = "Okafor Kosiso",
       Book = "All you need to get started in ASP.NET Core"
   };

   
   
   
[HttpPatch]
   public IActionResult Patched([FromBody]JsonPatchDocument< Librarys >patchedLibrary)
   {
       if (patchedLibrary == null)
        {
             return BadRequest();
       }

       var patched = librarys.Copy();

       patchedLibrary.ApplyTo(patched);

       var returnedValue = new
       {
           Old = librarys,
           Patched = patched
       };

       return Ok(returnedValue);
   }


Now that our API is ready, we shall be testing various patch JSON Patch. And we shall be using POSTMAN to send request to the API.


Testing Json Patch operations:

Testing the various Json Patch operation is quite easy, you do that by sending request to operation by sending request to /API/Librarys. It’s easy to test all JSON Patch operation, but in this article we shall be testing for REPLACE.


How to Replace an item

To replace an item in JSON patch, we have to supply the path of the item to replace.

PATCH /api/librarys
[
   {
     "op": "replace",
     "path": "/Book",
     "value": "Advanced Algorithm"
   }
]

Response:
{
   "Old": {
       "Author": "Okafor Kosiso",
       "Book": "All you need to get started in ASP.NET Core"
              
   },
   "patched": {
       "Author": "Okafor Kosiso",
       "Book": "Advanced Algorithm"                    ]
   }
}


Summary

ASP.NET Core supports JSON patch and it’s quite easy. Using JSON patch makes your request to be light and to scale in speed.

Comments

Popular posts from this blog

Top 2 ways to pass parameters to a view component

View components is a feature of ASP.NET Core MVC, that’s similar to partial view and child actions, one cool thing about view component it allows you to create reusable components with or without logic.
The purpose of this post is to show you how to pass view component as a parameter when invoking it from view and controller.
Another  cool thing about View Components is that it separates the logic of which markup to display from the markup itself. It’s a class that inherits from View component and implements Invoke and InvokeAsync Methods, the return type can vary, and that depends on largely what you intend to render.
Example of Simple View Component
public class ItemViewComponent : ViewComponent
{
   public IViewComponentResult Invoke()
   {
       return View();
   }
}
To use the View Component, we have to invoke the Item View component from _Layout.cshtml

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…