Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not accept additional fields in incoming JSON request body

I have a Spring Boot server that listens on endpoint. I accept @RequestBody as an object:

class Body {
   private String name;
}

I want it to accept requests like:

{
   "name": "some_name"
}

However, it also accepts:

{
   "name": "some_name",
   "dummy key":"dummy key value"
}

In that case I want it to throw error. How can I achieve it?

like image 488
Kyeiv Avatar asked Oct 12 '25 04:10

Kyeiv


1 Answers

TL;DR;

If you want the controller to return an error when the RequestBody does not match what you are expecting it is enough to add this to your application.properties:

spring.jackson.deserialization.fail-on-unknown-properties=true

This will return a default 400 response on malformed requests.

The @Valid annotation

Adding the @Valid annotation to your controller performs constraint validation and it will only fail when, for example, you mark a field as to be of a maximum value of 1 but the request tries to set it to 2. As per the docs:

Marks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are validated when the property, method parameter or method return type is validated.

But since you are not using any of the tools provided by jakarta.validation this annotation will have no effect on your code.

like image 102
Arturo Mendes Avatar answered Oct 14 '25 18:10

Arturo Mendes