1
votes

Let's suppose to have an HTTP POST that accept as input a JSON with some data and it must validate these data. The method should return also a validation message in the response body.

Ex.

{
   "A" : 1,
   "B" : 1,
   "C" : 3
}

Suppose to have some validation rules defined over the JSON, for example (A + B) should be less than C parameter.

I have some doubts about the HTTP status code.

  • If the JSON is valid the HTTP POST should returns 200
  • If the JSON is not valid (missing parameters or wrong types) the HTTP POST should returns 400

But in case the JSON is valid (there are all the requested parameters and the types are correct) but the parameters don't respect the defined rules (A + B < C) what should be the HTTP Status?

  • 200 and than an explanation in the response body?
  • 400 and the explanation in the response body?

Is there the need to differentiate the HTTP Status from the Validation rules Status?

Cheers

3

3 Answers

3
votes

That's what status code 422 ("Unprocessable Entity") has been designed for.

See https://www.greenbytes.de/tech/webdav/rfc4918.html#STATUS_422.

1
votes

It all depends on the use-case / functionality you want to achieve.

If you want to make it easy for others to work with valid messages, I would perhaps return 2xx only if the message is completely valid, and in all other cases return 4xx. In this case the caller does not need to parse the result, which makes it easy to work with.

If the use-case is to provide some analytic service that others will use to analyze messages, not specifically to use the message itself, then I would return 2xx with the result of the analysis unless the message can not be parsed (not a json for example), in which case 4xx is warranted.

1
votes

your response need to be 400 with the follwing message: "Bad Request: parameters don't respect the rules". 400 error