GET/POST Requst to REST API using Spring Boot

Vijesh picture Vijesh · Oct 2, 2018 · Viewed 14.4k times · Source

I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080. Now I want to make GET or POST request to the REST API address i.e https://api.myrestservice.com/users to get all users, using my locally running Spring Boot App i.e through http://localhost:8080/users. I am not getting how to redirect local app request to external server request.

Answer

Jitesh Shivnani picture Jitesh Shivnani · Oct 2, 2018

I hope I got your question right. You are trying get your local app to get data from app running on your server.

You can use the below sample code in your spring boot application.

private void getUsers() {

     final String uri = "https://api.myrestservice.com/users";
     RestTemplate restTemplate = new RestTemplate();
     Users result = restTemplate.getForObject(uri, Users.class);      
     System.out.println(result); 
}

Then your getUsers can be invoked by getUsers Controller in your spring boot app.

I am adding the reference if you want to look at more examples - https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/