Springboot – validate @RequestBody

We Are Going To Discuss About Springboot – validate @RequestBody. So lets Start this Java Article.

Springboot – validate @RequestBody

  1. Springboot – validate @RequestBody

    Add @NotNull annotation on a field (you may need to change type to Integer), and add @Valid annotation on the method parameter of the controller.
    Mono<String> question(@Valid @RequestBody Foo foo) { ... }

  2. Springboot – validate @RequestBody

    Add @NotNull annotation on a field (you may need to change type to Integer), and add @Valid annotation on the method parameter of the controller.
    Mono<String> question(@Valid @RequestBody Foo foo) { ... }

Solution 1

Add @NotNull annotation on a field (you may need to change type to Integer), and add @Valid annotation on the method parameter of the controller.

Mono<String> question(@Valid @RequestBody Foo foo) {
    ...
}
public class Foo {

    @NotNull
    private Integer important;
    private String something;

//constructors, getter, seters, toString
}

You can find more information here: https://lmonkiewicz.medium.com/the-power-of-spring-rest-api-validation-77be83edef

Original Author Of This Content

Solution 2

The already provided answer covers the answer.

However I would like to elaborate on one thing that you asked.

How to fail on this
“importantWithTypo”: 42,

2 aspects to it.

  1. you want to return a 4XX if a required field is not present (this can be achieved by the already given answer) — @NonNull/@NonEmpty in conjunction with @Validate annotation
  2. You want to error out on presence of an unknown field importantWithTypo. This can be achieved by jackson’s fail_on_unknown_properties property. (May be default is fail_on_unknown_properties = enabled, I havent checked so not sure).

Don’t do this 2nd thing. That will make your 2 services tightly coupled. By doing this fail_on_unknown_properties = enabled, you are forfeiting the potential opportunity to enhance the consumer/caller service in a nonbreaking fashion. You will have to coordinate both the apps releases.

Original Author Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment