REST HTTP status codes for failed validation or invalid duplicate

前端 未结 9 1862
借酒劲吻你
借酒劲吻你 2020-11-22 13:53

I am building an application with a REST-based API and have come to the point where I am specifying status codes for each requests.

What status code should i send for

9条回答
  •  一个人的身影
    2020-11-22 13:58

    200,300, 400, 500 are all very generic. If you want generic, 400 is OK.

    422 is used by an increasing number of APIs, and is even used by Rails out of the box.

    No matter which status code you pick for your API, someone will disagree. But I prefer 422 because I think of '400 + text status' as too generic. Also, you aren't taking advantage of a JSON-ready parser; in contrast, a 422 with a JSON response is very explicit, and a great deal of error information can be conveyed.

    Speaking of JSON response, I tend to standardize on the Rails error response for this case, which is:

    {
        "errors" :
        { 
            "arg1" : ["error msg 1", "error msg 2", ...]
            "arg2" : ["error msg 1", "error msg 2", ...]
        }
    }
    

    This format is perfect for form validation, which I consider the most complex case to support in terms of 'error reporting richness'. If your error structure is this, it will likely handle all your error reporting needs.

提交回复
热议问题