且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么 HTTP 响应代码用于失败的 POST 请求?

更新时间:2022-10-29 09:14:44

POST 请求不成功并且请求正文格式正确时,应该返回什么 HTTP 响应代码?

如果您的意思是请求有效负载的语法有效但由于数据无效而无法处理,您可以使用 422:

11.2.422无法处理的实体

422(不可处理实体)状态码表示服务器了解请求实体的内容类型(因此415(不支持的媒体类型)状态代码不合适),以及请求实体的语法是正确的(因此是 400(错误请求)状态代码不合适)但无法处理包含的指示.例如,如果 XML请求正文包含格式正确(即语法正确),但语义错误的 XML 指令.

记得在响应负载中提供一个很好的描述,解释负载有什么问题.有关如何报告 HTTP API 中的问题的详细信息,请参阅 RFC 7807.>


更新(根据评论)

POST 请求失败的原因更多是业务逻辑错误,例如账户余额太低,无法提取 5.00 美元".

对于您的 评论403409 会更合适.

6.5.3.403禁止

403(禁止)状态码表示服务器理解请求,但拒绝授权.希望的服务器公开请求被禁止的原因可以描述响应负载中的原因(如果有).[...]

6.5.8.409冲突

409(冲突)状态代码表示请求无法由于与目标的当前状态冲突而完成资源.此代码用于用户可能能够解决冲突并重新提交请求.服务器应该为用户生成一个包含足够信息的负载认识到冲突的根源.[...]

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.

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. [...]