We Are Going To Discuss About Springboot – validate @RequestBody. So lets Start this Java Article.
Springboot – validate @RequestBody
- 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) { ... }
- 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.
- 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
- 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.