Creating REST endpoints has become pretty popular. Bad format, missing required values, missing properties. How to handle it?
The best solution here is to fail fast, that is to validate the request as soon as possible, check everything we can when it comes to the request format, and if it is Validating json request body, return an error before we hit our business logic with the request. We have to ensure that all requests that are coming into it are valid.
The approach like this gives us two things. The second thing is that we can remove a lot of sanity checks from business logic, we can assume that all the data will be correct, everything that is required will be there. This simplifies the code a lot. Spring offers the simplest form of validation out of the box. With these simple annotations, Spring will validate all requests, and respond with Bad Request when the required parameter is missing or has a wrong type.
For example, if we declare a parameter as an Integer, and we will pass some kind of String in the request, we will also receive an error response. First, we have to annotate our object with all the constraints and requirements. If we have some nested objects there, we have to add Valid annotation on a field with this objects, so that it will be Validating json request body. JSR Validation gives a pretty broad set of validators out of the box.