Spring Boot REST Web Services Validation

Mahesh Bonagiri
4 min readJul 3, 2021

Validation is a common requirement in all the services. 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. Spring Boot provides strong support for this common, yet critical, task straight out of the box.

Let’s start

we will use Spring Initializr generate the base for our project, in my previous post i have explained how to get starting with Spring Boot REST web services.

Download and import the project to your eclipse. Eclipse will automatically download all required dependencies.

Create BooksController.java and Books.java as shown below.

Lets add constraints like @NotBlank, @NotEmpty, @NotNull, @Min,@Max etc.. to Book.java

Book.java

Open BooksController.java and update create method to add @Valid annotation (It is a Javax validation API). When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation and validates the argument.

While it’s really handy to have Spring Boot validating the Book object passed on to the create() method automatically, the missing facet of this process is how we process the validation results.

The @ExceptionHandler annotation allows us to handle specified types of exceptions through one single method. Therefore, we can use it for processing the validation errors:

We specified the MethodArgumentNotValidException exception as the exception to be handled. Consequently, Spring Boot will call this method when the specified Book object is invalid.

The method stores the name and post-validation error message of each invalid field in a Map. Next it sends the Map back to the client as a JSON representation for further processing.

Simply put, the REST controller allows us to easily process requests to different endpoints, validate Book objects, and send the responses in JSON format.

BooksController.java

Run our application, you should see “Started SpringbootRestInputValidationApplication in xxxx seconds” message.

Positive Scenario: Open the Postman and send a POST request with below input (all are valid inputs)

Application returns HTTP status code 200 means everything is OK.

Negative Scenario:

Open the Postman and send a POST request with below input (all are In valid inputs)

Negative inputs-Request

Application returns HTTP status code 400 Bad Request, means Input is Invalid.

400 Bad Request
Negative-Inputs-Response

When we create a RESTful services we need to think about consumer that how does the consumer know what is wrong. It is difficult to understand the message for the user. So we will now customize the message and make it more error specific.

Open Book.java file and add an attribute message=”Custome Message” to every required constraint annotation as shown below.

Open the Postman and repeat the same request, you should be able to see below customized messages.

Negative-Inputs-Response-with-CustomMessage

More about javax.validation.constraints can be found here.

Bonus Point:

Cross-site scripting (also known as XSS) is a web security vulnerability that works by manipulating a vulnerable web site so that it returns malicious JavaScript to users.

To prevent XSS attacks, When our application receives the POST /books call it should detect the suspicious values in free form text fields and reject the request. This will prevent from storing data that can potentially used later for an XSS attack.

we can use @Pattern and @Valid annotations for this purpose.

Conclusion:

If you would like to refer to the full code, do check https://github.com/projectk-user1/Springboot-learning.git

Please do refer my other articles on Spring boot

Feel free to provide your suggestions in comments section

--

--