What HTTP response code to use for failed POST request?

﹥>﹥吖頭↗ 提交于 2021-01-21 07:12:45

问题


What HTTP response code should be returned when a POST request was not successful and a request body was correctly formatted?

For successful POST request i am using 201 - Created, but there is no equivalent not created code.

I am thinking either 400 - bad request but that would actually point user that a request is poorly formatted or 304 - not modified.


回答1:


What HTTP response code should be returned when a POST request was not successful and a request body was correctly formatted?

If you mean the syntax of the request payload is valid but it cannot be processed due to invalid data, you can use 422:

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Remember to provide a good description in the response payload explaining what's wrong with the payload. Refer to the RFC 7807 for details on how to report problems in HTTP APIs.


Updates (according to the comments)

The reason why a POST request would fail is more of a business logic error, for example "account balance too low to withdraw 5.00 USD".

For the situation described in your comment, 403 or 409 would be a better fit.

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any). [...]

6.5.8. 409 Conflict

The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict. [...]



来源:https://stackoverflow.com/questions/47269601/what-http-response-code-to-use-for-failed-post-request

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