Spring boot lab (part 3): Using the RestTemplate
In the third part of this series on Spring Boot we will start implementing the core of the application using Spring Boot’s RestTemplate.
What will be done here?
We will add a service, that calls GitHub’s API using the RestTemplate.
Implementation
The REST controller
At first, we add a new class in the same package as the WelcomeController. This new controller exposes another endpoint (“/repos/some-username”). When the endpoint is called, the GithubRepositoryService in its turn calls the GitHub API.
The service
The following class is used to call GitHub’s API to retrieve information about the repositories owned by a specific user.
This seems to be all that is needed. However, the build fails with the following message:
Obviously, the field restTemplate in the GithubRepositoryService class cannot be initialized right now. The missing piece here is to create a bean of type RestTemplate which can be autowired into the service.
This can be fixed by adding a bean definition, e.g. to the SpringBootLabGithubHeroApplication class:
Now the restTemplate should be initialized correctly and the build should succeed.
After starting the application, you can access the new endpoint (“/repos/some-username)” list of GitHub repositories will be shown in json format.
Further examples are discussed in future tutorials. A fully working example is available at the link below.