RESTful service, how to respond if validation failed?

I have service that takes some entity and needs to save/update this entity:

http://myhost.com/rest/entity

I use POST and submit JSON. Inside service it detects that entity passed is not good. Not valid, order passed in with customer that doesn not exist, etc.

How should I reply? HttpCode.NotFound ? Or others? How do you reply to such things?


In our project in such situations we do the following:

  • Set response code to HTTP 400 Bad Request
  • Set response body to the following JSON: {"message":"%extended error message here%"}
  • But it's really very subjective.

    Also I'd suggest reading This blog article on RESTfull error handling - it describes many available options, so you can choose something for your taste.


    422 Unprocessable Entity, defined in WebDAV (RFC 4918):

    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 (ie, syntactically correct), but semantically erroneous, XML instructions.


    I think you should pick a client error code. 400 Bad Request or 403 Forbidden can be a good start

    链接地址: http://www.djcxy.com/p/45394.html

    上一篇: 如何处理REST API中的大量资源

    下一篇: RESTful服务,如果验证失败,如何回应?