DEV Community

Zer
Zer

Posted on

Spring Boot REST Basics : How to validate your request body

Overview

In software development, it is important to do some validation for security purposes and also lessen the unexpected errors, but it takes a lot of hours just to implement specific validation methods. In this post, I will share the easiest way on how to validate your request body in Spring Boot.

Let's get started

Add dependency

Add the spring boot starter validation to your project. You can do this by adding the code below to your pom.xml.

<dependency>             
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Update your controller

Let's say you have a login API that authenticates the user. All you need to do is add the @Valid annotation to your request body. For this example I added the @Valid annotation to my userLoginRequestModel. This signals Spring Boot to do some validation of the model.

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/login")
    public UserLoginResponseModel login(@Valid @RequestBody UserLoginRequestModel userLoginRequestModel) {
        return userService.login(userLoginRequestModel);
    }
}
Enter fullscreen mode Exit fullscreen mode

Update your model

In your model, all you need to add is the specific validation annotation that we want to implement. For this example, I used the @NotEmpty annotation to make sure the username and password is required. I also added the message parameter.

public class UserLoginRequestModel {
    @NotEmpty(message = "Username is required.")
    private String username;

    @NotEmpty(message = "Password is required.")
    private String password;

    //...
}

Enter fullscreen mode Exit fullscreen mode

There are a lot of validations you can use, such as @Min and @Max, make sure to check the documentation.

Update your exception handler

To display the validation results, It is better to handle the error in your exception handler method.

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
  MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
Enter fullscreen mode Exit fullscreen mode

Test

Now, try to test the validation in your API. The result should return something like this.

{
  "Username is required.",
  "Password is required."
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Spring Boot makes it way easier to do validation just by using the @Validannotation. No need to implement validation methods that sometimes may not work. So make sure to try this out.

Top comments (0)