Not sure where to make external API calls in my Spring MVC application

1.1k views Asked by At

First a disclaimer – I am very new to programming. This project is for what's more or less a capstone, and we're working in the Spring Boot framework (Java language, Thymeleaf views).

The overall gist of my program is this: a user fills out a form, and those parameters are used to make a call to the Yelp Fusion API.

I spent a lot of time figuring out how to make the API call, and sort of neglected to think about where to do it. It's currently in my Controller class, but now I'm not so sure if that's the best idea – maybe it should go in a Model or even a DTO? I'd appreciate any insight, as the general internet seems to be conflicted.

Here's the link to the repository on GitHub if that helps.

Thanks!

1

There are 1 answers

0
Pratik Sherke On BEST ANSWER

It is preferred to make any client calls or write business logic for the API in the Service layer.

In your case, you can create a service package and create some interface YelpClientCallService.java which is autowired in your controller, and a class YelpClientCallServiceImpl.java that implements the YelpClientCallService.java interface. Now, you can call the client API from this class and then perform business logic on the response received, or you can just return the response to the controller.

You can also annotate the service class as @Service instead of @Component. It is just a special name for @Component and will help in classification. For more details on package structure in Springboot you can check the below resources.

  1. Spring docs : this has the basic package structure that is followed.
  2. This medium blog is also decent to understand other aspects of project structure and best practices.