I am writing a RESTful API (json) in C# using WCF 4.0. Data is stored in a SQL Server 2012 db. One available call will allow clients to save objects, something like this:
PUT /object/123
{
Subject: "my subject",
Comment: "my comment"
}
That far all is ok. But sometimes the client only wants to update one of the parameters in an object. Like this:
PUT /object/123
{
Comment: "I changed my comment"
}
The question is: is there a best practice to make the update in the database table? How do I know what fields were supplied (given that some fields should be able to be null)? How do I write nice code that only update those columns that were supplied?
Generally I do it like this. Your first example should be a POST. POST tells you it’s a create. The PUT method will tell you it’s an update, in which case I update ALL fields of object with id 123. This means the client can just send you their entire object with any/all fields updated. You just blindly copy them.
I suppose if you didn’t want the overhead of sending all fields, you could check for a default value (null or empty string) and only update those fields which are not equal to that value.
also check this out:
Only update some properties on an EF entity that are not set to null