Spring Boot Rest Template Example
Sidd B
Posted on September 25, 2021
In this article, we will learn how to invoke or call Rest full API's in spring boot. Essentially we are going to write a simple client to consume a few public RESTful API's. RESTTemplate is for just that, Spring's RESTTemplate is used to write client applications to consume RESTful API
Table of Content
Consuming RESTful API in Spring Boot
In our earlier articles, we learned how to create rest full API's . In this article, we will learn how to invoke or call Rest full API's in spring boot. Essentially we are going to write a simple client to consume a few public RESTful API's. RESTTemplate is for just that, Spring's RESTTemplate is used to write client applications to consume RESTful API
In this article, we will consume two different public API. For that, we will write a standalone Spring Boot App, to consumes the REST API's as follows
API 1: Get all GitHub API's
GET https://api.github.com
API 2: Get all Github repositories for user bootng
GET https://api.github.com/users/bootng/repos
Technologies Used
- Java 11
- Apache Maven 3.5.0
- Spring Boot 2.2.6
- Eclipse IDE
Main Application Class
package com.javaexp;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@SpringBootApplicationpublic class ResttemplateApplication { private static final Logger log = LoggerFactory.getLogger(ResttemplateApplication.class); public static void main(String args[]) { log.info("about to call ResttemplateApplication.run()"); SpringApplication.run(ResttemplateApplication.class, args); log.info("completed executing ResttemplateApplication.run()"); }}
Our first REST client is as bellow, which calls a REST endpoint and then displays results in the console.
LoadAllGithubEndpoints.java
package com.bootng;import java.util.Iterator;import java.util.Map.Entry;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.web.client.RestTemplateBuilder;import org.springframework.core.annotation.Order;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Component;import org.springframework.web.client.RestTemplate;import com.fasterxml.jackson.databind.JsonNode;/** * This Class List all the endpoints from URL https://api.github.com * */@Component@Order(1)public class LoadAllGithubEndpoints implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(ResttemplateApplication.class); @Override public void run(String... args) throws Exception { log.info("about to call LoadAllEndpoint.run()"); RestTemplate restTemplate = new RestTemplateBuilder().build(); ResponseEntity<JsonNode> apis = restTemplate.getForEntity("https://api.github.com", JsonNode.class); StringBuilder result = new StringBuilder("\n List of Public API's"); apis.getBody().fields().next().getValue(); Iterator<Entry<String, JsonNode>> it = apis.getBody().fields(); while (it.hasNext()) { result.append("\n").append(it.next().getValue().asText()); } log.info(result.toString()); }}
Our second REST client is as bellow, which calls a REST endpoint and then displays all the repositories for user bootng in the console.
LoadGithubRepo
package com.bootng;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.web.client.RestTemplateBuilder;import org.springframework.core.annotation.Order;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Component;import org.springframework.web.client.RestTemplate;import com.fasterxml.jackson.databind.JsonNode;@Component@Order(2)public class LoadGithubRepo implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(ResttemplateApplication.class); @Override public void run(String... args) throws Exception { log.info("about to call LoadGithubRepo.run()"); RestTemplate restTemplate = new RestTemplateBuilder().build(); ResponseEntity<JsonNode> repos = restTemplate .getForEntity("https://api.github.com/users/bootng/repos", JsonNode.class); int counter = 1; StringBuilder result = new StringBuilder("\n List of Repositories"); if (repos.getBody().isArray()) { for(JsonNode jsonNode : repos.getBody()) { result.append("\n Repo ").append(counter++).append("::"); result.append(jsonNode.get("name").asText()); } } log.info(result.toString()); }}
Notice that LoadGithubRepo is marked with annotation Order(2) and LoadAllGithubEndpoints is marked with annotation Order(1). That means Spring will execute LoadAllGithubEndpoints first and then LoadGithubRepo.
Building and Running the application
mvn clean installmvn spring-boot:run
Console Output
20-June-18 16:25:17:627 INFO main c.b.ResttemplateApplication:27 - about to call LoadAllEndpoint.run()
20-June-18 16:25:18:570 INFO main c.b.ResttemplateApplication:40 -
List of Public API's
https://api.github.com/user
https://github.com/settings/connections/applications{/client\_id}
https://api.github.com/authorizations
https://api.github.com/search/code?q={query}{&page,per\_page,sort,order}
https://api.github.com/search/commits?q={query}{&page,per\_page,sort,order}
https://api.github.com/user/emails
https://api.github.com/emojis
https://api.github.com/events
https://api.github.com/feeds
https://api.github.com/user/followers
https://api.github.com/user/following{/target}
https://api.github.com/gists{/gist\_id}
https://api.github.com/hub
https://api.github.com/search/issues?q={query}{&page,per\_page,sort,order}
https://api.github.com/issues
https://api.github.com/user/keys
https://api.github.com/search/labels?q={query}&repository\_id={repository\_id}{&page,per\_page}
https://api.github.com/notifications
https://api.github.com/orgs/{org}
https://api.github.com/orgs/{org}/repos{?type,page,per\_page,sort}
https://api.github.com/orgs/{org}/teams
https://api.github.com/gists/public
https://api.github.com/rate\_limit
https://api.github.com/repos/{owner}/{repo}
https://api.github.com/search/repositories?q={query}{&page,per\_page,sort,order}
https://api.github.com/user/repos{?type,page,per\_page,sort}
https://api.github.com/user/starred{/owner}{/repo}
https://api.github.com/gists/starred
https://api.github.com/users/{user}
https://api.github.com/user/orgs
https://api.github.com/users/{user}/repos{?type,page,per\_page,sort}
https://api.github.com/search/users?q={query}{&page,per\_page,sort,order}
20-June-18 16:25:18:570 INFO main c.b.ResttemplateApplication:21 - about to call LoadGithubRepo.run()
20-June-18 16:25:19:069 INFO main c.b.ResttemplateApplication:36 -
List of Repositories
Repo 1::angular-word-merger
Repo 2::hansini-static-deploy
Repo 3::JUnit5-examples
Repo 4::okhttp
Repo 5::spring-boot-web-start
Repo 6::springboot\_docker
20-June-18 16:25:19:071 INFO main c.b.ResttemplateApplication:57 - Started ResttemplateApplication in 3.382 seconds (JVM running for 6.625)
20-June-18 16:25:19:071 INFO main c.b.ResttemplateApplication:17 - completed executing ResttemplateApplication.run()
Get source code and build
- git clone https://github.com/siddharthagit/spring-boot-resttemplate
- cd spring-boot-resttemplate
- mvn clean install
- mvn spring-boot:run
Summary
- In this article, we saw how to write a simple REST client using RESTTEmplate in Spring Boot.
- In our next article, we will see more use cases of using RESTTemplate like for POST/PUT, etc.
References
Posted on September 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.