Contents

Spring REST parameter validation

Written by: David Vlijmincx

Introduction

In this post, we look at how to apply bean validation to the input of REST calls in Spring Boot. With bean validation you can validate that the objects passed to your REST end-points are valid and ready to use.

Spring dependency

To use Spring validation to validate the input of the REST methods, you need to include the following dependency:

1
2
3
4
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

This dependency adds the Hibernate validator to your project. Spring uses this validator to verify that your beans are valid.

Using bean validation

The next step is to apply the validation you need to the fields you want to have validated. In the following examples, I validate that the username is not null and has a minimum length of 2 and a maximum length of 5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class User{

    @NotNull
    @Size(min=2, max= 5)
    private String username;

    public User(String username) {
        this.username = username;
    }

    public User() {
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Take a look at the Jakarta specification if you want to know more about validation and the built-in annotations.

Validate input of REST calls

You need to annotate the parameter you want to validate with @Valid. Only parameters with @Valid are checked to see if they are indeed valid. The user parameter will be validated in the following example before the method is entered.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@RestController
public class SimpleRestController {


    @PostMapping("create")
    void createUser(@RequestBody @Valid User user){
        // User is valid at this point
        saveUser(user);
    }
}

Inside the createUser method, you can be sure that the User instance is valid.

Validation on a Record

Starting with Hibernate Validator 8.0.0.Final, you can now validate records in Java. This means you can apply annotations like this:

1
record User (@NotNull @Size(min=2, max= 5) String username){ }

These instances will be validated like any other.

Conclusion

This post showed you how you can use Spring bean validation with REST end-points. To start with validation, you need to add the spring-boot-starter-validation dependency. Using the Jakarta validation annotations, you can validate the input parameters of your methods.