Validating Request Data — Using Bean Validation

When developing a REST API, it's important to validate request data, and in case of invalid data, return a 4xx response with a precise body containing field-wise error details. In this section, we'll look at how to do that in a Spring application.

Let’s take an example. Say we have a signup form, as below:

And, we receive the input in a controller method, as below:

The service method that’s being called above could look as below:

So, if a field is blank, how to send an error response?

Using Bean Validation

A good way to validate input data, like the signup form above, is to use bean validation. Spring framework has good support for it. In fact, a Spring Boot application auto-configures its Hibernate implementation.

So, to validate our signup form using bean validation, first annotate its fields with constraint annotations like @NotBlank, @Email and @Size:

Then, annotate the SignupForm parameter in the handler with @Valid, as below:

Now, in case of any errors, Spring would throw an exception instead of executing the controller code. The exception can then be handled in a cross-functional way as we have learned in last section.

So far so good. But, some people prefer to do the validation in the service layer. Validation is business logic, after all, and so service layer seems ideal for it. Doing it in the service layer also allows us to do some pre-processing in the controller — see this for example.

How to do that? Join me in the next lesson!