Spring Boot RestTemplate GET Example

In this, Spring Boot RestTemplate GET request example, learn to use RestTemplate to invoke HTTP GET API and verify the response status code and the response entity body.

To create the rest APIs, use the sourcecode provided in spring boot rest api example.

1. Setup

Start with including the latest version of spring-boot-starter-web dependency in the project.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

In the given example, I will first write the rest API code and then write the unit test which invokes the rest API and verifies the API response.

@GetMapping("users")
public ResponseEntity<List<User>> getAll() { ... }

@GetMapping("users/{id}")
public ResponseEntity<User> getById(@PathVariable long id) { ... }

2. Configure RestTemplate

The simplest way to create a RestTemplate instance is its default constructor.

RestTemplate restTemplate = new RestTemplate();

Alternatively, we can use RestTemplateBuilder to configure a custom instance and later autowire into other beans.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
 
	return builder
		.setConnectTimeout(Duration.ofMillis(3000))
		.setReadTimeout(Duration.ofMillis(3000))
		.build();
}

3. Using RestTemplate

The RestTemplate provides the following methods for executing GET APIs:

  • getForObject() – retrieves a representation by doing a GET on the URL. The response (if any) is unmarshalled to the given class type and returned.
  • getForEntity() – retrieve a representation as ResponseEntity by doing a GET on the URL.
  • exchange() – execute the specified HttpEntity and return the response as ResponseEntity.
  • execute() – execute the HttpMethod to the given URI template, prepare the request with the RequestCallback, and read the response with a ResponseExtractor.

3.1. getForEntity() and getForObject()

The getForEntity() method returns a ResponseEntity that can be used to check the response status, headers and body. In following example, we are retrieving the response as String and parsing it later.

String userJson = restTemplate.getForObject("/users/{id}", String.class, Map.of("id", "1"));
ResponseEntity<String> responseEntity = restTemplate.getForEntity("/users/{id}", String.class, Map.of("id", "1"));

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(responseEntity.getBody());

If we want to retrieve the response as POJO, we can do it as follows:

//User Collection

User[] usersArray = restTemplate.getForObject("/users", User[].class);
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity("/users", User[].class);

// User by Id

User user = restTemplate.getForObject("/users/{id}", User.class, Map.of("id", "1"));
ResponseEntity<User> responseEntityUser = restTemplate.getForEntity("/users/{id}", User.class, Map.of("id", "1"));

3.2. exchange()

If the GET API accepts request headers, we need to use the generic exchange() API. In this example, we are sending two headers. X-COM-PERSIST header is mandatory and X-COM-LOCATION is optional. The example invokes GET API with mandatory headers and verifies the API response code and the response body.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("X-COM-PERSIST", "NO");
headers.set("X-COM-LOCATION", "USA");

HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<User[]> responseEntity = restTemplate.exchange("/users", HttpMethod.GET, entity, User[].class);

Let me know if you have any queries in this spring boot RestTemplate get API example.

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode