Not getting exception while passing invalid json request body to rest api in spring boot

Viewed 2334

I have created one rest API in spring-boot, the problem is that I am taking 4 parameters as a requestbody argument as a JSON object.

Now if I pass the JSON object with 5 parameters than my API still call, no assertion exception occurs while serializing the JSON object. I have one dto class as below with constructor

public class testDto{
   @NotNull(message = "fistName can not be null.")
   private String fistName;
   @NotNull(message = "lastName can not be null.")
   private String lastName;
   private String nickName;

   public testDto() {
    }

    public testDto(@NotNull(message = "fistName can not be null.") final String fistName ,@NotNull(message = "lastName can not be null.") final String lastName , final String nickName){
      super();
      this.fistName = fistName;
      this.lastName = lastName;
      this.nickName = nickName;
    }
}

My restapi as below,

@PostMapping(path ={ "/api/v1/user"}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> saveUser(
            @Valid @RequestBody(required = true) final testDto dto) throws Exception {
}

Now while calling my API I am passing request body as below

{
      "fistName" : "abc",
      "lastName" : "xyz",
      "nickName" : "pqr",
      "age" : 25
}

Now here when I pass age parameter and call the API, my API still working instead of throwing an exception for No any constructor found as I have passed age which is not a member of my dto class.

Expected result: don't allow to call API Actual result: Allow me to call API

I have also tried with assertion exception declaration and binding exception but not getting any success.

also set the property

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
2 Answers

Spring Boot uses Jackson to map the JSON payload to an instance of your testDto class. By default, Jackson is configured to ignore entries in the JSON that it cannot map to the DTO. This follows the robustness principle or Postel's law as it's also known.

You can configure Jackson to fail when it cannot map an entry in the JSON to a property on a DTO by adding the following line to your application's application.properties file in src/main/resources:

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

What to do when the request is invalid json but the values are correct ex:

{
      "fistName" : "abc",
      "lastName" : "xyz",
      "nickName" : "pqr",
      "nickName" : "pqrs"
}

Now in this case it is taking the last one and mapping it

Related