1

When i call the following api it gives 400 bad request even if we given valid data with request body. If i remove the @Valid annotation then it works fine. can any one help me here what is going wrong.

I am sending following request body with Postman { "x": "a", "y": "b" }

 import javax.validation.Valid;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import com.magicsoftware.restapi.exception.TestPOJO;
    import io.swagger.v3.oas.annotations.parameters.RequestBody;

@RestController
@Validated
@RequestMapping(path = "/Test")
public class TestController {

    @GetMapping(value = "/test1")
    public String test1(@Valid @RequestBody TestPOJO tpj) {
        if (tpj instanceof TestPOJO) {
            System.out.println("Correct data format passed ");
        }
        return "working1";

    }
}

    import javax.validation.constraints.NotNull;

public class TestPOJO {
    @NotNull(message="X should not be null")
    private String x;

    @NotNull(message="Y should not be null")
    private String y;


    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }   
}
  • What is the actual error messag? What path are you posting to? – Antoniossss Jun 13 '22 at 10:05
  • https://stackoverflow.com/questions/57325466/not-able-to-validate-request-body-in-spring-boot-with-valid can be same with your problem. – oisleyen Jun 13 '22 at 10:06
  • @Antoniossss, error message is -: 400 "Bad Request" and i am posting following data with path -: "path: http://localhost:8080/Test/test1" "body:"{ "x": "a", "y": "b" }" – Dattatray Satpute Jun 13 '22 at 10:20
  • Not enough, stacktrace would be needed – Antoniossss Jun 13 '22 at 10:21
  • @Antoniossss please see the trace log "org.springframework.validation.BeanPropertyBindingResult: 2 errors Field error in object 'testPOJO' on field 'y': rejected value [null]; codes [NotNull.testPOJO.y,NotNull.y,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [testPOJO.y,y]; arguments []; default message [y]]; default message [Y should not be null] Field error in object 'testPOJO' on field 'x': rejected value [null]; codes [NotNull.testPOJO.x,NotNull.x,NotNull.java.lang.String,NotNull]; arguments " – Dattatray Satpute Jun 13 '22 at 10:22

1 Answers1

1

You are importing RequestBody from io.swagger.v3.oas.annotations.parameters.RequestBody; but it shoud be imported from

org.springframework.web.bind.annotation.RequestBody;
Nemanja
  • 3,295
  • 11
  • 15