开发者

HTTP: Pattern to partially update a resource (that accepts empty strings)?

If there's a resource of type Foo with unique ID 36 at location:

http://example.com/foo/36

and a Foo contains several pieces of variable data (var1, var2, etc.), some of them strings;

What's the preferred pattern for updating a partial set of the resource's variables via HTTP (given that we may wish to set some to be empty strings)?

(The problem being that a form value of an empty string is not considered "successful" by the W3C standard and is not required to be submitted by the browser. If the empty value is not sent, the server doesn't know that we wanted to set that variable to an empty string.)

I've thought of the following options:

  1. POST to http://example.com/foo/36 with a li开发者_如何学JAVAst of name/value pairs for variables that have a "successful" value, and an extra parameter, the value of which is a comma-separated list of values that we wish to set to be an empty string.

  2. PUT to http://example.com/foo/36/var1;var2;var3, specifying the complete set of values that we want to update as part of the URI. Any specified name not received as a PUT argument will be set to an empty string.

  3. Send separate PUT requests to each variable at http://example.com/foo/36/var1, http://example.com/foo/36/var2, etc. Expose every variable as a separate resource (very explicit, but involves lots of requests).

But none of these seem intuitive, elegant or standard to me.


Your mentioned approach are good ideas to bypass the parameter restriction you mentioned, but they are not that standard. Thinking that your api should to be client friendly, I would go the more common approach to use resource formats like JSON or XML:

  • They are more "explicit" representations of your domain-data
  • You can present null-values better (for instance either empty or non-existent XML-tag).

The browser could send the data by AJAX in JSON format.

for create you would sent complete data:


POST /foo
...
{"var1":"x","var2":2,"var3":"hello"}

for (partial) update:


PUT /foo/123
...
{"var1":"y","var2":null}

In partial update "var3" would be preserved.

For updates I prefer to always send complete data (not partial ones like above), because it eases mapping + implementation. But there are cases where partial updates are necessary.


What I would do is to modify somewhat the PUT semantics so that only the sent value/pairs are updated in the resource: if the resource doesn't exist, create it with the info in the PUT request; if the resource exists, update only the passed name/value pairs.

I even think partial updates would be a nice addition to the rest architecture. Just use some HTTP header to indicate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜