What's the currently recommended way of performing partial updates with Web API?
Asked Answered
E

1

22

I'm wondering how to implement partial updates with ASP.NET Web API's RESTful interface? Let's say for example we are passing objects over the wire of the following structure:

public class Person {
    public int Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
}

How would one support updating just parts of a Person at a time, for example the Email property? Is it recommended to implement this via OData and the PATCH verb, or would it be better to implement PATCH oneself?

Exaction answered 5/1, 2013 at 23:43 Comment(0)
K
31

There is no support in the current latest stable release of Web API (from August 2012). So if all you want to use is Web API RTM, you would have to implement the whole plumbing yourself.

With that said, OData prerelease package supports partial updates very nicely through the new Delta<T> object. Currently the Microsoft.AspNet.WebApi.OData package is at RC version already (0.3) and can be obtained from here: http://www.nuget.org/packages/Microsoft.AspNet.WebApi.OData

Once you install that, you can then use that accordingly:

[AcceptVerbs("PATCH")]
public void Patch(int id, Delta<Person> person)
{
    var personFromDb = _personRepository.Get(id);
    person.Patch(personFromDb);
    _personRepository.Save();
}

And you'd call it from the client like this:

$.ajax({
    url: 'api/person/1',
    type: 'PATCH',
    data: JSON.stringify(obj),
    dataType: 'json',
    contentType: 'application/json',
    success: function(callback) {            
       //handle errors, do stuff yada yada yada
    }
});

The obvious advantage of this is that it works for any property, and you don't have to care whether you update Email or Username or whatnot.

You might also want to look into this post, as it shows a very similar technique http://techbrij.com/http-patch-request-asp-net-webapi

EDIT (more info): In order to just use PATCH, you do not need to enable anything OData related, except for adding the OData package - to get access to the Delta<TEntityType> object.

You can then do this:

public class ValuesController : ApiController
{
    private static List<Item> items = new List<Item> {new Item {Id = 1, Age = 1, Name = "Abc"}, new Item {Id = 2, Age = 10, Name = "Def"}, new Item {Id = 3, Age = 100, Name = "Ghj"}};

    public Item Get(int id)
    {
        return items.Find(i => i.Id == id);
    }

    [AcceptVerbs("PATCH")]
    public void Patch(int id, Delta<Item> item)
    {
        var itemDb = items.Find(i => i.Id == id);
        item.Patch(itemDb);
    }
}

If your item is, let's say:

{
    "Id": 3,
    "Name": "hello",
    "Age": 100
}

You can PATCH to /api/values/3 with:

{
    "Name": "changed!"
}

and that will correctly update your object.

Delta<TEntity> will keep track of the changes for you. It is a dynamic class that acts as a lightweight proxy for your Type and will understand the differences between the original object (i.e. from the DB) and the one passed by the client.

This WILL NOT affect the rest of your API in any way (except of course replacing the DLLs with newer ones to facilitate the OData package dependencies).

I have added a sample project to demonstrate the work of PATCH + Delta - you can grab it here (it.s VS2012) https://www.dropbox.com/s/hq7wt3a2w84egbh/MvcApplication3.zip

Kaohsiung answered 8/1, 2013 at 16:19 Comment(8)
I looked into OData as a way to get support for PATCH. However, is it possible to just make use of Delta + PATCH without implementing the OData protocol in general? I'm not interested in making an OData API, I just want PATCH support.Exaction
no Delta<T> will not work without the ODataMediaTypeFormatter, so you need to at least add the oData package and call configuration.EnableOData(GetEdmModel()); More info here: blogs.msdn.com/b/alexj/archive/2012/11/02/….Kaohsiung
But how does this impact my REST API in practice? Will it work according to the OData protocol, or can I implement PATCH without adapting my published API to OData?Exaction
actually my comment was wrong :) you CAN use Patch+Delta without enabling OData bits. The Delta<T> is just a proxy that keeps track of the dependencies. I edited the answer and added a sample projectKaohsiung
This isn't working for me at the moment, is this broken after the update of the OData package? The code runs and I can step into the method in the debugger but the patch doesn't apply any changes.Kucik
Maybe you should say it works only for non-primitive data types. It's unable to patch int value (Age in your demo).Torquay
Doesn't work with the latest stable WebAPI 2 release. I honestly don't want to bring in ODataMediaTypeFormatter I need this to work with JSON.NET. I would suggest upvoting this feature request: aspnetwebstack.codeplex.com/workitem/777Ferromagnetism
This SO answer is from Youssef Moussaoui, who I believe worked on Web API at Microsoft: https://mcmap.net/q/246811/-how-to-use-delta-lt-t-gt-from-microsoft-asp-net-web-api-odata-with-code-first-jsonmediatypeformatter . In it he states that Delta<T> is designed to work only with OData and if it works with any other media formatter that's by accident rather than by design.Safford

© 2022 - 2024 — McMap. All rights reserved.