Right HTTP status code to wrong input

前端 未结 6 1314
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 11:58

What is optimal HTTP response Code when not reporting 200 (everything OK) but error in input?

Like, you submit some data to server, and it will response that your da

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 12:21

    According to the below scenario ,

    Let's say that someone makes a request to your server with data that is in the correct format, but is simply not "good" data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using "password" as their password). then the status code could be either 400 or 422 ?

    Until now, I would have returned a "400 Bad Request", which, according to the w3.org, means:

    The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

    This description doesn't quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it's probably your best bet.

    Recently, however, Someone from my Dev team pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code "422 Unprocessable Entity" as defined in the HTTP extension for WebDAV. HTTP status code 422 states:

    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.

    Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

提交回复
热议问题