Issue
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;
}
}
Solution
You are importing RequestBody
from io.swagger.v3.oas.annotations.parameters.RequestBody;
but it shoud be imported from
org.springframework.web.bind.annotation.RequestBody;
Answered By - Nemanja
Answer Checked By - Robin (JavaFixing Admin)