Best way of sending REST responses in spring boot

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.

1 answer

  • answered 2018-01-11 20:50 zero01alpha

    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"
    }