Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestController POST 400 Bad Request

I have a Spring RestController that any attempt to post to it returns 400 Bad Request despite seeing the correct data being sent in Chrome Developer Tools. The @Valid annotation is kicking it out because the ParameterDTO object is not being populated at all.

My Controller

@RestController
@RequestMapping(path = "/api/parameters", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public class ParameterResource {

    private final ParameterService parameterService;

    @Autowired
    public ParameterResource(ParameterService parameterService) {
        this.parameterService = parameterService;
    }

    @GetMapping
    public ResponseEntity<?> getParameters(@RequestParam(value = "subGroupId", required = false) Integer subGroupId) {
        if (subGroupId != null) {
            return ResponseEntity.ok(parameterService.getParameters(subGroupId));
        }
        return ResponseEntity.ok(parameterService.getParameters());
    }

    @PostMapping
    public ResponseEntity<?> createParameter(@Valid ParameterDTO parameterData) {
        int id = parameterService.saveParameter(parameterData);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(id).toUri();
        return ResponseEntity.created(uri).build();
    }

    @GetMapping(path = "/levels")
    public ResponseEntity<?> getParameterLevels() {
        return ResponseEntity.ok(ParameterLevels.getParameterLevelMap());
    }

    @GetMapping(path = "/levels/{id}/values")
    public ResponseEntity<?> getLevelValues(@PathVariable("id") int levelId) {
        return ResponseEntity.ok(parameterService.getParameterLevelValues(levelId));
    }

    @GetMapping(path = "/types")
    public ResponseEntity<?> getParameterTypes() {
        return ResponseEntity.ok(parameterService.getParameterTypes());
    }
}

I was using axios from JavaScript and though my problem might be there but I have the same issue using Postman. I am setting the Content-Type and Accept header. It seems like Spring is not deserializing the data at all.

enter image description here

enter image description here

like image 783
greyfox Avatar asked Feb 23 '17 19:02

greyfox


1 Answers

You need to add @RequestBody annotation before ParameterDTO parameterData declaration, like below:

    @PostMapping
    public ResponseEntity<?> createParameter(@RequestBody @Valid ParameterDTO parameterData) {
        int id = parameterService.saveParameter(parameterData);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(id).toUri();
        return ResponseEntity.created(uri).build();
    }
like image 163
bart.s Avatar answered Oct 22 '22 23:10

bart.s