开发者

What should be the reponse code when validation errors happen?

I'm implementing an API. The API accepts/returns JSON content type. Now, suppose that the data submitted by some POST request is not valid, like a missing 开发者_如何学Cattribute, or a duplication exists for the same data. What is the standard HTML response code in that case?


The error lies on the client side, so you want to use a 4xx status code. I'd go with 400 - Bad Request:

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


There are two answers:

If you have submitted a form, just return 200 - OK with HTML explaining why the object was not created.

If you have an API you should use the following

200 OK

  • When the request was OK and returned the proper data.

201 CREATED

  • The call was successful and the new object created.

400 BAD REQUEST

  • Invalid request URI
  • Invalid HTTP Header
  • Receiving an unsupported, nonstandard parameter
  • Receiving an invalid HTTP Message Body

401 UNAUTHORIZED

  • Authorization problems. E.g. wrong API key, etc.

403 FORBIDDEN

  • Properly authorized, but not allowed.

404 NOT FOUND

  • The resource does not exist (e.g. on Read or Update)

405 METHOD NOT ALLOWED

  • Use in situations that a given REST method is not allowed. E.g. a POST on a single resource, or a DELETE on the entire collection of resources.

409 CONFLICT

  • When an update fails, send "Conflict" to allow the client side to resolve the conflict themselves and retry.

500 INTERNAL SERVER ERROR

  • Internal error. This is the default code that is used for all unrecognized errors.

501 NOT IMPLEMENTED

  • Use for expected, but not yet implemented features.


The closest i can find would be 400 Bad Request.


As Ariejan said you should base your API in the HTTP codes already defined. If you want to send a error message the best way should be not use the HTTP message, but better include the message in the response body, JSON formatted.


422 Unprocessable Entity (see RFC 4918, Section 11.2)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜