I am writing a simple Java Spring Boot test application to call a REST API. The main purpose at this point is to quickly get something working and to also help refresh my memory/knowledge on making REST calls from a Java application.
I've worked with Spring Boot in the past, as well as calling REST APIs, but it's been a few years and I no longer have access to the applications I had a hand in writing. I've forgotten a lot of the details.
Here is what I have so far:
Application.java:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
TestController.java:
@RestController
public class TestController {
@Autowired
private RestTemplate template;
@GetMapping("/groups")
public Object[] getAllGroups(String url) {
Object[] groups = template.getForObject(url, Object[].class);
return groups;
}
}
I'm not even at the point of trying to run this. Many of the online examples I've found leave out the details of how a URL is "provided" to the REST calls.
I also don't understand how the resource path /groups
in @GetMapping
is mapped to the REST call when the RestTemplate
object is used in the method. What is the purpose of the resource path in the annotation? How does it "fit" with the template call?
I'm assuming that the template should probably be used in a @Service
, rather than in the controller, but I'm just trying to get this working and understand how it works.
On a related note, what other techniques are there to make the REST API URL available to the application besides passing it in to the RestTemplate
object? Can this be done in some sort of configuration file? I've forgotten so much and am having a hard time finding an example that covers the finer details that are usually glossed over, if not completely left out.
CodePudding user response:
You're misunderstanding the purpose of a @RestController
vs RestTemplate
.
Annotating a class with @RestController
and @GetMapping
annotations provides a REST interface which can service HTTP requests.
Inside the implementation of getAllGroups
you would normally use a service or a repository to get data from a DB, and return it to the client who had made the HTTP request.
A RestTemplate
instance is used to make HTTP requests to other REST interfaces, provided by other servers. It wouldn't normally be used in the implementation of a @RestController
, unless some of the information returned came from some other microservice, for example.
The REST API URL is for the use of clients calling your REST API, not for use within your controller.