Spring RestTemplate.getForEntity()

By Arvind Rai, April 19, 2020
This page will walk through Spring RestTemplate.getForEntity() method example. The getForEntity method retrieves resources from the given URI or URL templates. It returns response as ResponseEntity using which we can get response status code, response body etc. To fetch data on the basis of some key properties, we can send them as path variables. We need to use URI template and pass a Map or Object varargs to getForEntity method to expand it on URI template. Now let us discuss using getForEntity in our REST client application.

1. Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.5.RELEASE
3. Spring Boot 2.2.6.RELEASE
4. Maven 3.5.2

2. Maven Dependencies

Find the Maven dependencies to run the example.
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency> 

3. Using getForEntity()

Find the getForEntity method declaration with URI + responseType from Spring doc.
ResponseEntity<T> getForEntity(URI url, Class<T> responseType) 
url: URI to fetch data.
responseType: Type of object returned by getForEntity method.

Client code
URI uri = new URI("http://localhost:8080/employee");

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity(uri, Employee[].class); 
Server code
@GetMapping("employee")
public ResponseEntity<List<Employee>> getAllEmployees() {
  ------
} 

4. URI Variables as Object Varargs

Find the getForEntity method declaration with url + responseType + uriVariables as Object Varargs from Spring doc.
ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) 
url: String url template to fetch data.
responseType: Type of object returned by getForEntity method.
uriVariables: URI variables as Object Varargs.

Client code
String url = "http://localhost:8080/employee/{id}";
Integer empId= 101;
ResponseEntity<Employee> responseEntity = restTemplate.getForEntity(url, Employee.class, empId); 
Server code
@GetMapping("employee/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") Integer empId) {
   ------
} 

5. URI Variables as Map

Find the getForEntity method declaration with url + responseType + uriVariables as Map from Spring doc.
ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String,?> uriVariables) 
uriVariables: URI variables as Map.

Client code
String url = "http://localhost:8080/employee/{profile}/{tech}";
Map<String, String> map = new HashMap<>();
map.put("profile", "Developer");
map.put("tech", "Java");

ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity(url, Employee[].class, map); 
In the above code the URI variables has been passed as Map. If we want to use object varargs in the above code, we can do it as following.
String profile = "Developer";
String tech = "Java";
ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity(url, Employee[].class, profile, tech); 
Now find the Server code.
@GetMapping("employee/{profile}/{tech}")
public ResponseEntity<List<Employee>> getEmployeesByProfileNTech(@PathVariable("profile") String profile,
			@PathVariable("tech") String technology) {
  ------
} 

6. Complete Example

Find the client code.
RestClientUtil.java
package com.concretepage.client;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.concretepage.domain.Employee;

public class RestClientUtil {

	public void getEmployeeDemo1() throws URISyntaxException {
		URI uri = new URI("http://localhost:8080/employee");

		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity(uri, Employee[].class);

		System.out.println("Status Code: " + responseEntity.getStatusCode());
		for (Employee e : responseEntity.getBody()) {
			System.out.println(e);
		}
	}
	
	public void getEmployeeDemo2() {
		String url = "http://localhost:8080/employee/{id}";
        
		Integer empId= 101;
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<Employee> responseEntity = restTemplate.getForEntity(url, Employee.class, empId);

		System.out.println("Status Code: " + responseEntity.getStatusCode());
		Employee emp = responseEntity.getBody();
		System.out.println(emp);
	}	
	
	public void getEmployeeDemo3() {
		String url = "http://localhost:8080/employee/{profile}/{tech}";

		Map<String, String> map = new HashMap<>();
		map.put("profile", "Developer");
		map.put("tech", "Java");

		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity(url, Employee[].class, map);

		System.out.println("Status Code: " + responseEntity.getStatusCode());
		for (Employee e : responseEntity.getBody()) {
			System.out.println(e);
		}
	}

	public static void main(String args[]) throws URISyntaxException {
		RestClientUtil util = new RestClientUtil();
		util.getEmployeeDemo1();
		util.getEmployeeDemo2();
		util.getEmployeeDemo3();
	}
} 

Find the Server code.
EmployeeController.java
package com.concretepage.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.concretepage.domain.Employee;
import com.concretepage.service.EmployeeService;

@RestController
public class EmployeeController {
	@Autowired
	private EmployeeService empService;

	@GetMapping("employee")
	public ResponseEntity<List<Employee>> getAllEmployees() {
		List<Employee> list = empService.getAllEmployees();
		return new ResponseEntity<List<Employee>>(list, HttpStatus.OK);
	}	
	
	@GetMapping("employee/{id}")
	public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") Integer empId) {
		Employee emp = empService.getEmployeeById(empId);
		return new ResponseEntity<Employee>(emp, HttpStatus.OK);
	}
	
	@GetMapping("employee/{profile}/{tech}")
	public ResponseEntity<List<Employee>> getEmployeesByProfileNTech(@PathVariable("profile") String profile,
			@PathVariable("tech") String technology) {
		List<Employee> list = empService.getEmployeesByProfileNTech(profile, technology);
		return new ResponseEntity<List<Employee>>(list, HttpStatus.OK);
	}
} 
Employee.java
package com.concretepage.domain;
public class Employee {
	private int empId;
	private String name;
	private String city;
	public Employee() {}
	public Employee(int empId, String name, String city) {
		this.empId = empId;
		this.name = name;
		this.city = city;
	}
        //Setters and Getters
} 
EmployeeService.java
package com.concretepage.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import com.concretepage.domain.Employee;

@Service
public class EmployeeService {
	public Employee getEmployeeById(int empId) {
		// Perform database operation
		System.out.println("empId: " + empId);
		return new Employee(101, "Lakshman", "Agra");
	}	
	public List<Employee> getEmployeesByProfileNTech(String profile, String technology) {
		// Perform database operation
		System.out.println(profile);
		System.out.println(technology);
		Employee e1 = new Employee(101, "Lakshman", "Agra");
		Employee e2 = new Employee(102, "Bharat", "Mathura");
		return Arrays.asList(e1, e2);
	}
	public List<Employee> getAllEmployees() {
		// Perform database operation
		Employee e1 = new Employee(101, "Lakshman", "Agra");
		Employee e2 = new Employee(102, "Bharat", "Mathura");
		Employee e3 = new Employee(103, "Shatrughan", "Noida");
		return Arrays.asList(e1, e2, e3);
	}	
} 
Find the Output for getEmployeeDemo1() method of RestClientUtil class.
Status Code: 200 OK
101, Lakshman, Agra
102, Bharat, Mathura
103, Shatrughan, Noida 

7. Run Application

Download the project and run the following command from root folder of the project using command prompt.
mvn spring-boot:run 
Now run RestClientUtil as Java Application.

8. Reference

Spring RestTemplate

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us