Partial updating

Put actions are used to replace a resource with another one. Therefore, the client must add the whole entity in the body payload of the request. If our entity is a complex object, keeping the entire entity in memory may cause performance issues. It is possible to avoid these problems by implementing a Patch action instead. The Patch action usually modifies an existing resource without replacing it, therefore you are able to specify only one the field you want to update. Let's see how we can perform this kind of action in ASP.NET Core.

First of all, let's add a new field to our Order.cs class:

using System;
using System.Collections.Generic;

namespace SampleAPI.Models
{
public class Order
{
public Guid Id { get; set; }
public IEnumerable<string> ItemsIds { get; set; }
public string Currency { get; set; }
}
}

Now, the Order class contains an additional field that represents the currency of our orders. Let's create a Patch action in our OrderController. The code we are going to implement uses two NuGet packages that provide the support for the PATCH method and all the types that help us to perform the operations related to that type of HTTP verb. We can add the package to our project by running the following instructions in the SampleAPI project folder:

dotnet add package Microsoft.AspNetCore.JsonPatch
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson

The first NuGet package provides the JsonPatchDocument class type, the second package enables the NewtonsoftJson serializer needed by the PATCH operation support. In addition, we should also enable the NewtonsoftJson serializer into the application by adding the following extension method in the Startup class:

public class Startup
{
...

public void ConfigureServices(IServiceCollection services)
{
services
.AddSingleton<IOrderRepository, MemoryOrderRepository>()
.AddControllers()
.AddNewtonsoftJson();
}

  Furthermore, it is possible to implement the Patch action method in the following way:

[HttpPatch("{id:guid}")] 
public IActionResult Patch(Guid id, JsonPatchDocument<Order> requestOp)
{
var order = _orderRepository.Get(id);
if (order == null)
{
return NotFound(new { Message = $"Item with id {id} not exist." });
}

requestOp.ApplyTo(order);
_orderRepository.Update(id, order);

return Ok();
}

The aforementioned code has three key points:

  • The action method reacts to the HttpPatch verb requests. Just like the Put action, it accepts a Guid as the input parameter, which identifies the target resource.
  • The action method also accepts a JsonPatchDocument as the payload of the body. The JsonPatchDocument class is a generic class that is part of the ASP.NET Core Framework. More specifically, our action uses the JsonPatchDocument<Order> type to implement operations on our Order class.
  • The action method applies the JsonPatchDocument class using the ApplyTo method, which merges the changes in the request to our target resource. Finally, it updates the repository.

The JsonPatchDocument class accepts a specific request schema. For example, the following curl operation performs a partial update through the PATCH verb:

curl -X PATCH 
https://localhost:5001/api/order/5749c944-239c-4c0c-8549-2232cf585473
-H 'Content-Type: application/json'
-d '[
{
"op": "replace", "path": "/itemsIds", "value" : [1,2]
}
]' -k

In this case, the body payload is a JSON array of objects: every object is composed of an op field, a path, and a value.

The op field describes the operation to perform on our target, path refers to the name of our field, and value is the replacement for our target. In this case, the request will replace the itemsIds field with the value [1,2]. Furthermore, the op field accepts a bunch of operations on data, including add and remove. As we saw previously, the syntax is almost the same as it was in the previous example:

[{
"op": "add", "path": "/itemsIds", "value" : [3]
},
{
"op": "remove", "path": "/itemsIds"
}]
JsonPatchDocument is compliant with the specification of the Internet Engineering Task Force (IETF), an organization that promotes internet standards. You can find out more information about the Patch document syntax in the declaration of the standard at the following link: https://tools.ietf.org/html/rfc5789. All the other specifications about the HTTP method that we've discussed in this chapter can also be found here. 
You should pay attention when using the JsonPatchDocument object. The client may request to update a read-only field or a non-existent field. Furthermore, the JsonPatchDocument type requires a validation step. This problem is usually solved by creating a custom data transfer object (DTO) model for this kind of request.

Let's move on to the next subsection, which describes the deleting process for the resources and how to implement the resulting action method in the controller class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.143.181