besmart besmart - 3 years ago 88
reST (reStructuredText) Question

Spring MVC - REST Api, keep getting 400 Bad Request when trying to POST

i have a REST api service which should receive POST calls.

I'm using POSTMAN to test them, but i keep getting a 400 Bad Request Error, with no body, maybe i'm building bad my controller...

This is the controller

@PostMapping("/object/delete")
public ResponseEntity<?> deleteObject(@RequestBody long objectId) {
logger.debug("controller hit");
Object o = service.findByObjectId(objectId);
if(o!=null){

service.deleteObject(object);

return new ResponseEntity<>(HttpStatus.OK);
}

return new ResponseEntity<>(HttpStatus.NOT_FOUND);

}


Using
@RequestBody
i should send the request in JSON, in this way:

{
"objectId":100
}


But i get a 400 error, and the strange think is that my logger
logger.debug("controller hit");
it's not printed in logs...

Answer Source

Sending { "objectId":100 } would result in receiving an object X with an objectId attribute in your java method.

If you just need to send an id, you can use @PathVariable

@PostMapping("/object/{id}/delete")
public ResponseEntity<?> deleteObject(@PathVariable("id") long objectId) {

Also, consider using DeleteMapping instead of PostMapping to delete an object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download