Spring Boot RESTful API – Request Validation

Spring Boot RESTful API – Request Validation

Spring Boot RESTful API – Request Validation

Go Back to Course Outline

Repositories

We will start by opening the CategoryController class.

[open CategoryController class]

To enable automated validation we must annotate the class with @Validated. More annotations are available from javax.validation.constraints package like size, email, not-null, etc.

As an example, let’s check the method oneCode. Notice that it has a @Size(min = 3, max = 50) annotation, which will check if the given code has a length of at least 3 characters and a max of 50.

How about for the request body? First, we need to add constraints to the model’s fields such as @NotEmpty on BusinessEntity.code. And to trigger the validation we must add @Valid to the request parameter – this is one crucial step that is often missed by new developers. Now, let’s run create a category in Postman with an empty code. But before that run the app first.

There are times when we want to customize the error message, we can achieve that by overriding the validator.

[open MessageSourceConfig class]

Here we have a validator producer, which sets the messageSource from a customized MessageSource producer.

Try running a create category test again with code length less 3. Notice that it throws a message “code size must be between 3 and 50”.

[open messages.properties file]

To end this video, don’t forget to add the spring-boot-starter-validation dependency in your pom file.

Ja ne.

Leave a Reply