HTTP status code for update and delete?
我应该为UPDATE
( PUT
)和DELETE
(例如成功更新产品)设置什么状态代码?
For a PUT request: HTTP 200 or HTTP 204 should imply "resource updated successfully".
For a DELETE request: HTTP 200 or HTTP 204 should imply "resource deleted successfully". HTTP 202 can also be returned which would imply that the instruction was accepted by the server and the "resource was marked for deletion".
9.6 PUT
If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes > SHOULD be sent to indicate successful completion of the request.
9.7 DELETE
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
Source: w3.org: HTTP/1.1 Method Definitions
HTTP 200 OK: Standard response for successful HTTP requests. The actual response will depend on the request method used.
HTTP 204 No Content: The server successfully processed the request, but is not returning any content
Source: List of HTTP status codes: 2xx Success
Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).
Long answer: here's a complete decision diagram (click to magnify).
Source: https://github.com/for-GET/http-decision-diagram
Here are some Tips:
DELETE
200 (if you want send some additional data in the Response) or 204 (recommended).
202 Operation deleted has not been committed yet.
If there's nothing to delete, use 204 or 404 (DELETE operation is idempotent, delete an already deleted item is operation successful, so you can return 204 , but it's true that idempotent doesn't necessarily imply the same response)
Other errors:
PUT
If you're updating an element of a collection
The referenced element doesn't exists:
404 If you don't want to create elements via PUT.
400 Bad Request (Malformed syntax or a bad query more common than in case of DELETE).
上一篇: 如何使用java.net.URLConnection来触发和处理HTTP请求
下一篇: 用于更新和删除的HTTP状态码?