Best way of sending REST responses in spring boot
Personally I think that returning ResponseEntity
is going to be the best choice for a lot of cases. A little more readable way of doing it in my opinion is to use the handy status methods on ResponseEntity
like this
@PostMapping()
public ResponseEntity post(@Valid @RequestBody Item item, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return ResponseEntity.badRequest().body(new ModelErrors(bindingResult));
}
return ResponseEntity.created().body(itemService.addItem(item));
}
Alternatively, you can use the status
method passing a HttpStatus
or status code like this
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ModelErrors(bindingResult));
ResponseEntity.status(201).body(itemService.addItem(item));
Another option is to just return whatever type you'd like without using ResponseEntity
, but this gives you a lot less control over the response and requires that you have the proper MessageConverter
configuration (you can read up on that here).
A simple example might look like this
@RequestMapping("/hotdog")
public Hotdog hotdog() {
return new Hotdog("mystery meat", "ketchup, mustard");
}
and if everything is configured correctly you'd end up with a response like this
{
"content": "mystery meat",
"condiments": "ketchup, mustard"
}
Related videos on Youtube
kubi
Updated on June 04, 2022Comments
-
kubi almost 2 years
What is the best way to send rest responses in spring boot? Also how should i manage sending status codes to do it properly?
Currently i do it using ResponseEntity but i doubt this is the most elegant way.
Sample code:
@PostMapping() public ResponseEntity post(@Valid @RequestBody Item item, BindingResult bindingResult){ if (bindingResult.hasErrors()){ return new ResponseEntity<>(new ModelErrors(bindingResult), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(itemService.addItem(item), HttpStatus.CREATED); }
ModelErrors class extends a HashMap class and just fetches and wraps the BindingResult's error messages.
-
kubi over 6 yearsDidn't even know i could do that xd. Thanks. So the ResponseEntity isn't a bad way of sending responses? Is there a more popular way of doing that?
-
secondbreakfast over 6 yearsI think
ResponseEntity
is the way to go. I have updated my answer with another option.