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.
Spring provides a few primary ways to return custom status codes from its Controller classes: using a ResponseEntity. using the @ResponseStatus annotation on exception classes, and. using the @ControllerAdvice and @ExceptionHandler annotations.
Using custom exception class you can return different HTTP status code and dto objects.
ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.
Advantages of using Spring Boot A few benefits of using Spring Boot for your REST APIs include: No requirement for complex XML configurations. Embedded Tomcat server to run Spring Boot applications. An auto-configuration feature by Spring Boot that configures your application automatically for certain dependencies.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With