joydip_kanjilal
Contributor

How to do partial updates to REST API resources

how-to
Jul 10, 20174 mins
Small and Medium BusinessSoftware DevelopmentWeb Development

Take advantage of HTTP PATCH to partially update resources and transfer less data over the wire

thread weave needle
Credit: Thinkstock

The HTTP verb named PATCH can be used for partial updates, i.e., when you would like to update just a few fields of a resource. While you could update a resource “partially” using HTTP PUT, by sending the entire resource with the updated values, that is potentially problematic. At the very least, you might end up consuming more network bandwidth than necessary.

For partial updates, HTTP PATCH is easier and safer, and ASP.NET Web API provides excellent support for HTTP PATCH requests. This article will discuss how we can use PATCH to perform partial updates when working with RESTful services using Web API.

PATCH vs. PUT

The HTTP PATCH method should be used whenever you would like to change or update just a small part of the state of the resource. You should use the PUT method only when you would like to replace the resource in its entirety. Note that PATCH is not a replacement for PUT or POST, but just a way of applying a delta update to a resource representation. Roy Fielding, who authored the REST architectural style and many web standards, said that he created PATCH because “partial PUT is never RESTful.”

Let’s look at a good example of a PATCH request. Imagine you have a model named Customer and not all of its members are editable. ASP.NET Web API incorporates nice support for HTTP PATCH requests using the Delta class, which was included as part of the OData additions. We will cover how to use the Delta class in a later post. In the section that follows, we will examine how we can implement HTTP PATCH support in Web API in the simplest way.

Implementing HTTP PATCH in WebAPI

Let’s now get into a bit of code. Create a new Web API project in Visual Studio. In the new project you have created, create a controller named CustomerController (you can leave it as empty for now) and the following Customer model class.

public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

Now, suppose only the two properties City and Country in the Customer model are editable. Let’s create a delta request class to update the Customer model. We’ll call it the CustomerPatchRequest class.

public class CustomerPatchRequest
    {
        public int Id { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

The following method illustrates how you can use the CustomerPatchRequest class to update a customer using a PATCH request.

[HttpPatch]
    public IHttpActionResult PatchCustomer([FromBody] CustomerPatchRequest request)
    {
        var customer = customersList.FirstOrDefault(c => c.Id == request.Id);
        if( customer == null)
            return NotFound();
        else
        {
            customer.City = request.City;
            customer.Country = request.Country;
        }
        return Ok();
    }

Note how no state is changed and a HTTP 404 is returned if the customer being searched is not found in the list. If the customer is found, a delta change is performed on the customer object and then a HTTP 200 is returned. Ideally, you should persist the data after altering the object’s state.

The customersList object is a list of customer instances. It is populated as shown in the code snippet below.

public static List<Customer> customersList = new List<Customer>()
    {
         new Customer()
         {
             Id = 1, FirstName="Steve", LastName="Smith",
             City ="Madrid", Country ="Spain"
         },
         new Customer()
         {
             Id = 2, FirstName="Samuel" ,LastName="Clarke",
             City ="Austin", Country ="USA"
         },
    };

You can call this Web API method via Fiddler. To do this, select PATCH as the HTTP Verb, specify the URL in the Composer window, and specify the following in the request body.

{
”Id”: 19,
”City”:”New York”,
”Country”:”USA”
}

Finally, specify the content type in the Composer window as shown in the code snippet below.

Content-Type: application/json

Here is the complete code listing of the CustomerController for your reference.

public class CustomerController : ApiController
    {
        public static List<Customer> customersList = new List<Customer>()
        {
            new Customer()
            {
                Id = 1, FirstName="Steve", LastName="Smith", City ="Madrid", Country ="Spain"
            },
            new Customer()
            {
                Id = 2, FirstName="Samuel" ,LastName="Clarke", City ="Austin", Country ="USA"
            },
        };

        [HttpPatch]
        public IHttpActionResult PatchCustomer([FromBody] CustomerPatchRequest request)
        {
            var customer = customersList.FirstOrDefault(c => c.Id == request.Id);
            if( customer == null)
                return NotFound();
            else
            {
                customer.City = request.City;
                customer.Country = request.Country;
            }
            return Ok();
        }
    }

HTTP PATCH is a nice way to update a resource by specifying only the properties that have changed. There are many ways in which HTTP PATCH can be implemented in a RESTful web API. This article presented the simplest way. In a future post, we will examine how we can take advantage of the JsonPatch library to implement HTTP PATCH support.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author