Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call another rest api from my server in Spring-Boot

I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a specific user on an event.

Does Retrofit have any method to achieve this? If not, how I can do that?

like image 1000
Mahdi Avatar asked Feb 21 '17 10:02

Mahdi


People also ask

How do I call REST API to another REST API?

Spring boot supports calling one rest service to another rest service using the RestTemplate class. RestTemplate is a synchronised client side class that is responsible for calling another rest service. RestTemplate supports all HTTP methods such as GET, POST, DELET, PUT, HEAD, etc.


2 Answers

This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

private static void getEmployees() {     final String uri = "http://localhost:8080/springrestexample/employees.xml";      RestTemplate restTemplate = new RestTemplate();     String result = restTemplate.getForObject(uri, String.class);      System.out.println(result); } 
like image 68
Torsten N. Avatar answered Sep 20 '22 03:09

Torsten N.


Modern Spring 5+ answer using WebClient instead of RestTemplate.

Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).

@Bean public WebClient localApiClient() {     return WebClient.create("http://localhost:8080/api/v3"); } 

Inject and use the bean from your service(s).

@Service public class UserService {      private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);      private final WebClient localApiClient;      @Autowired     public UserService(WebClient localApiClient) {         this.localApiClient = localApiClient;     }      public User getUser(long id) {         return localApiClient                 .get()                 .uri("/users/" + id)                 .retrieve()                 .bodyToMono(User.class)                 .block(REQUEST_TIMEOUT);     }  } 
like image 32
Snackoverflow Avatar answered Sep 21 '22 03:09

Snackoverflow