Using HTTP 304 in response to POST

限于喜欢 提交于 2019-12-08 14:45:15

问题


I have a REST API that allows modification of resources using HTTP POST. It's possible that a client may submit a POST request that results in no modification of the resource. I'm thinking about using the 304 response generally used for conditional responses to indicate that the request had no effect. I haven't been able to find any examples of this being done, so I figured I'd ask here and see if anyone else is doing this or has an opinion about it.


回答1:


After some consideration, I've decided to stick to a normal 200 response with the unchanged resource entity. My initial intent was to provide a concise way to indicate to the client that the resource was not modified. As I thought more about it I realized that in order to do anything useful with the 304 response, they would have to already have a cached version and in that case it would be trivial to compare the version of the cached copy with the version returned in a 200 response.




回答2:


I have a REST API that allows modification of resources using HTTP POST. It's possible that a client may submit a POST request that results in no modification of the resource.

HTTP POST in the RESTful approach implies a creation of a resource, not a modification. For modification you should use HTTP PUT.

Solution of your problem is HTTP Status 200 OK when something was modified and HTTP Status 204 No Content when there was no modification. According to:

The common use case is to return 204 as a result of a PUT request, updating a resource, without changing the current content of the page displayed to the user. If the resource is created, 201 Created is returned instead. If the page should be changed to the newly updated page, the 200 should be used instead.

-- MDN web docs


For example:

-- Request
POST /people HTTP/1.1
Content-Type: application/json

{
    "name": "John"
}

-- Response
HTTP/1.1 201 Created
Location: /people/1
-- Request
PUT /people/1 HTTP/1.1
Content-Type: application/json

{
    "name": "John"
}

-- Response
HTTP/1.1 204 No Content
-- Request
PUT /people/1 HTTP/1.1
Content-Type: application/json

{
    "name": "Robert"
}

-- Response
HTTP/1.1 200 OK
Content-Type: application/json

{
    "name": "Robert"
}


来源:https://stackoverflow.com/questions/20059297/using-http-304-in-response-to-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!