I have some doubts when to return a 400 Http Code in any rest api. I explain the next three cases:
- When some of parameters values dont match with the requirements, for example, the length of a string, or a range for a number I would return a 400
- When a user wants to execute some "action" in our system but before it, we apply some businness logic to validate this request and if its valid we execute that action, if the validation is KO, should we return 400?. I would
- The final one and more confusing to me, what about if we expose some rest method call that its purpose is just to validate something with businnes logic rules, like for example we expose a method in order the client can call us to validate the shopping of some items, should we return 400 in this case if any of the bussiness validation rules did not pass? I think I would not because the final goal of this request is to validate something and this has been executed succesfully although in the validation process some of the bussiness validation rules did not passed.
Do you agree? Thanks
CodePudding user response:
For 1) and 2) a 400 http status code should be returned.
For 3) it is depending on the business validation rule. If it is due to user rights, 403 would be a proper http status code. If something is due to resources that are not present (any more) 404 would be the status code to choose. Also 409 is a status code that could be useful in many business rule scenarios. In any case where no other 4xx status code seems indented, use 400.
Look here for a complete list of http status codes and the description for them: https://datatracker.ietf.org/doc/html/rfc7231#section-6.5
CodePudding user response:
The basic principle is to return a 400 HTTP status code whenever the client's request is not as expected (missing mandatory parameters, malformed content, etc.)
So, for case 1) you should return 400.
For case 2) and 3), it depends on the specific validation rule. For example, if your validation rule is about the structure or the values of the request's content or something else that the client can fix, then you can return 400.
If the validation rule involves some way the authorization context, you should use 401, 403, or even 404. Take a look at this article for more details: https://auth0.com/blog/forbidden-unauthorized-http-status-codes/