Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call another api from same app in spring boot

I have two RestControllers for user and Company.

  • CompanyController: fetch from and store company information to companies table using service and repo level.

  • UsersController : It is used to fetch and store users.

  • Relationship: Each user is associated with company(User hasOne company).

When new User get registered, we need to fetch company information by id and associate with user profile.

For this, I have one endpoint in CompanyController, named getCompanyInfo. I have to call that endpoint to fetch company data while saving user profile.

How to call another API from same app in Spring Boot?

like image 319
Sachin Avatar asked Oct 27 '25 23:10

Sachin


1 Answers

Why not are you calling Company service directly(if both controller exists in same application)? It will be more faster than calling company controller.

Your controller will look like this:

@RestController
public class UsersController {
    @Autowired
    private CompanyService companyService;

    @RequestMapping("/register")
    public ResponseEntity<User> registerUser(){
        //Do whatever you want
        CompanyInfo companyInfo = companyService.getCompanyInfo();
       //Do whatever you want
    }
}

If you still want to directly call Company Controller, then you can do something like this:

@RestController
public class UsersController {
    @Autowired
    private RestTemplate template;

    @RequestMapping("/register")
    public ResponseEntity<User> registerUser(){
        ResponseEntity<CompanyInfo> companyInfoResponse = template.getForObject("Url for getCompanyInfo() method", CompanyInfo.class);
        CompanyInfo companyInfo = companyInfoResponse.getBody();
        //Do whatever you want
    }
}
like image 143
Afridi Avatar answered Oct 30 '25 07:10

Afridi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!