Home > Software engineering >  Calling other REST services in controller or service class in springboot?
Calling other REST services in controller or service class in springboot?

Time:12-12

I am trying to implement a shopping cart checkout() service that needs to make a call into two other rest services , one is to call products REST service to check final prices and then another is to make payment via Payments REST service. Should I be making these REST calls in my spring controller or spring service class?

CodePudding user response:

It is best to separate the different concerns within the service itself. The controller in its nature, is responsible for mapping http requests and should not contain business logic as such.

It would be best to move the REST calls to the service layer of the checkout service.

However there is still room for improvement. Instead of the service layer making the REST calls, a sort of communicator module can be used to make the REST calls or handle the communication to the other services. Because today we might be using REST, tomorrow we can move to use gRPC etc. So it would be best to move the communications to another module.

Some code to bootstrap the structure;

Checkout controller

class CheckoutController {
    @Autowired
    private CheckoutService checkoutService;

    @PostMapping("/checkout")
    public string performCheckout(CheckoutDto checkoutDto){
         checkoutService.performCheckout(checkoutDto);
    }
}

Checkout service

class CheckoutService {
   @Autowired
   private PriceCheckerCommunicator priceCheckerCommunicator;

   void performCheckout(CheckoutDto checkoutDto){
        priceCheckerCommunicator.checkPrices(checkoutDto.getProductIds());
        // the same will be done with the payment service as well
   }
}

Price checker communicator

interface PriceCheckerCommunicator {
     // the implementation of the interface will be calling the price checker service using REST call
     void checkPrices(List<Long> productIds);
}

Here is an overview of the overall architecture; enter image description here

  • Related