Using HTTP 304 in response to POST

2019-06-15 07:29发布

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.

2条回答
我命由我不由天
2楼-- · 2019-06-15 08:22

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.

查看更多
地球回转人心会变
3楼-- · 2019-06-15 08:23

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"
}
查看更多
登录 后发表回答