top of page

HttpPut Or HttpPatch in ASP.Net Core ?



The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.


The HTTP PATCH request method applies partial modifications to a resource. A PATCH request is considered a set of instructions on how to modify a resource.


In simple words, “When a client needs to replace an existing Resource completely it should use PUT , but when only a part of Resource is needed to be updated it should use PATCH”.


In ASP.Net core

To achieve HttpPatch in ASP.net core WebAPI we have to make use of 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.


The specification defines 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.


Learn by coding…

In this tutorial, I am going to demonstrate “replace” operation. So let’s start by creating a ASP.Net core WebApi in Visual Studio.


Add reference of following packages to the project:

Microsoft.AspNetCore.JsonPatchMicrosoft.AspNetCore.Mvc.NewtonsoftJson

Add following code to Startup.cs

services.AddControllers()
        .AddNewtonsoftJson();

Add a class called “Person”

public class Person
{
  public int Id { get; set; }
  public string Name { get; set;}
  public string Contact { get; set; }
}

Add controller named “PersonController.cs” and define Get and Post request methods.

[HttpGet]
public IEnumerable<Person> Get()
{
 return _context.Persons.ToList();
}[HttpPost]
public Person Post([FromBody] Person person)
{
 _context.Add(person);
 _context.SaveChanges();
 return person;
}

Let’s add definition for HttpPut and HttpPatch.

[HttpPut]
public IActionResult Update([FromBody] Person person)
{
 _context.Update(person);
 _context.SaveChanges();  var patched = _context.Persons.FirstOrDefault(a => a.Id ==  person.Id);
    
 var model = new
 {
  sent = person,
  after = patched
 }; 
 return Ok(model);
}


HttpPatch

[HttpPatch("{personId}")]
public IActionResult Patch(int personId, [FromBody] JsonPatchDocument<Person> patch)
{
  var fromDb = _context.Persons.FirstOrDefault(a => a.Id ==   personId);
 
 var original = fromDb.Copy();
 patch.ApplyTo(fromDb, ModelState);
            
 var isValid = TryValidateModel(fromDb);
 if (!isValid)
 {
   return BadRequest(ModelState);
 } _context.Update(fromDb);
 _context.SaveChanges(); var model = new
 {
   original,
   patched = fromDb
 };  return Ok(model);
}

Okay enough code let’s see some action..


Run the app by Hitting F5.


You will see following swagger page.


Swagger UI


And first add a person using “POST” request.


Post request


Let’s do the “PUT” request to update the Person


PUT request


as you can see when we use put we had to send complete person object along with changed fields.


Let’s do the “PATCH” request now.

PATCH request


for patch request you have to send the data in JSONPatch format as defined in the specification.


Request

PATCH /api/Persons
[     
    {       
       "op": "replace",       
       "path": "/contact",       
       "value": "Alice.Smith.patch@mail.com"  
    } 
]

Response

{
  "original": {
    "id": 1,
    "name": "Alice Smith",
    "contact": "Alice.Smith.Put@mail.com"
  },
  "patched": {
    "id": 1,
    "name": "Alice Smith",
    "contact": "Alice.Smith.patch@mail.com"
  }
}

as you can see we have to send only the information which is required to be patched on the whole object.


Summary

You can take the advantage of HTTP PATCH to update part of resources and reduce the payload which is required to send the over the wire.


You can update the resource without having to know about rest of the object values.



Source: Medium - Nitesh Singhal


The Tech Platform

0 comments

Comments


bottom of page