Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for RestController?

Code convention says no logic in the controllers. All should be handled in the service layer. My question is especially about returning ResponseEntity.

Should it be handled in RestController or in Service layer?

I tried both ways. I think RestController is the suitable place to return ResponseEntity. Because we are using mappings in the RestController.

On the other hand, we know the controllers should not include any logic.

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return ResponseEntity.ok(employeeService.findEmployeeById(id);
}

or

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return employeeService.findEmployeeById(id);
}

ControllerAdvice for exception handling is my another concern. Which way is the best to use?

Thanks for your advance.

like image 704
Cihangir Avatar asked Jul 31 '19 05:07

Cihangir


People also ask

When should I use RestController?

@RestController Annotation: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client.


2 Answers

Status Code, Response Body, Headers are one of the core parts for REST

The controller should be concerned with accepting the request, asking the correct domain service to process the request, and handing off the response to the correct place.

It's right that controllers should not perform all business logic here but sending the HTTP response should be done in Controller instead of service.

Although Status code can be sent using @ResponseStatus(HttpStatus.XXX) which might not be helpful for in scenarios where we have to send Status Code according to the conditions. You can create custom ResponseDTO which generally have body, message and status code.

public ResponseEntity<ResponseDTO> method() {
    return new ResponseEntity<ResponseDTO>(response,response.getStatus()); 
}
like image 30
Romil Patel Avatar answered Sep 20 '22 22:09

Romil Patel


Code convention says no logic in the controllers.

Not really. Code convention says each layer has to perform itself logic which it is responsible of.
Computing the result, retrieving data requested/needed by the request is clearly not the rest controller job but sending an http response, what returning ResponseEntity does is its job. So this looks the correct way :

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return ResponseEntity.ok(employeeService.findEmployeeById(id);
}

If the ResponseEntity was produced by your service, your service would be coupled with the Http layer. Not desirable and make it less reusable as a service.

like image 117
davidxxx Avatar answered Sep 21 '22 22:09

davidxxx