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?

aknuds1
  • 57,609
  • 57
  • 177
  • 299

1 Answers1

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

Filip W
  • 26,577
  • 6
  • 89
  • 80
  • 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. – aknuds1 Jan 08 '13 at 18:17
  • 1
    no Delta will not work without the ODataMediaTypeFormatter, so you need to at least add the oData package and call configuration.EnableOData(GetEdmModel()); More info here: http://blogs.msdn.com/b/alexj/archive/2012/11/02/odata-in-webapi-microsoft-asp-net-web-api-odata-0-2-0-alpha-release.aspx. – Filip W Jan 08 '13 at 18:24
  • 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? – aknuds1 Jan 08 '13 at 18:28
  • 2
    actually my comment was wrong :) you CAN use Patch+Delta without enabling OData bits. The Delta is just a proxy that keeps track of the dependencies. I edited the answer and added a sample project – Filip W Jan 08 '13 at 19:22
  • 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. – BenCr Nov 06 '13 at 00:47
  • 2
    Maybe you should say it works only for non-primitive data types. It's unable to patch int value (Age in your demo). – Pavel Hodek May 27 '14 at 06:54
  • 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: http://aspnetwebstack.codeplex.com/workitem/777 – Abhijeet Patel Nov 18 '15 at 03:37
  • This SO answer is from Youssef Moussaoui, who I believe worked on Web API at Microsoft: http://stackoverflow.com/a/14734273/216440 . In it he states that Delta is designed to work only with OData and if it works with any other media formatter that's by accident rather than by design. – Simon Tewsi Jan 20 '17 at 12:29