Spring RestTemplate (with Examples)

We learned to build Spring REST API for XML representation and JSON representation. Now let us learn to build Spring REST client using the Spring RestTemplate to consume the REST APIs that we have written in the linked examples.

Note: Spring docs recommend to use the non-blocking, reactive WebClient which offers efficient support for both sync, async and streaming scenarios. RestTemplate will be deprecated in the future versions.

1. Spring RestTemplate

Accessing the REST APIs inside a Spring application revolves around the use of the Spring RestTemplate class. The RestTemplate class is designed on the same principles as the many other Spring *Template classes (e.g., JdbcTemplate, JmsTemplate ), providing a simplified approach with default behaviors for performing complex tasks.

Given that the RestTemplate class is a synchronous client and designed to call REST services. It should come as no surprise that its primary methods are closely tied to REST’s underpinnings, which are the HTTP protocol’s methods HEAD, GET, POST, PUT, DELETE, and OPTIONS.

2. How to Build RestTemplate

The given below are few examples to create RestTemplate bean in the application. We are only looking at very simple bean definitions.

2.1. Using RestTemplateBuilder

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

2.2. Using SimpleClientHttpRequestFactory

@Bean
public RestTemplate restTemplate() {
 
	var factory = new SimpleClientHttpRequestFactory();
	factory.setConnectTimeout(3000);
	factory.setReadTimeout(3000);
	return new RestTemplate(factory);
}
@Autowired
CloseableHttpClient httpClient;
 
@Value("${api.host.baseurl}")
private String apiHost;
 
@Bean
public RestTemplate restTemplate() {

	RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost));
	return restTemplate;
}
 
@Bean
@ConditionalOnMissingBean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {

	HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
			= new HttpComponentsClientHttpRequestFactory();
	clientHttpRequestFactory.setHttpClient(httpClient);
	return clientHttpRequestFactory;
}

Read More: RestTemplate Configuration with HttpClient.

2.4. Injecting RestTemplate Bean

To inject the RestTemplate bean, use the well known @Autowired annotation. If you have multiple beans of type RestTemplate with different configurations, use the @Qualifier annotation as well.

@Autowired
private RestTemplate restTemplate;

3. Spring RestTemplate – HTTP GET Example

Available methods for executing GET APIs are::

  • getForObject(url, classType) – retrieve a representation by doing a GET on the URL. The response (if any) is unmarshalled to given class type and returned.
  • getForEntity(url, responseType) – retrieve a representation as ResponseEntity by doing a GET on the URL.
  • exchange(url, httpMethod, requestEntity, responseType) – execute the specified RequestEntity and return the response as ResponseEntity.
  • execute(url, httpMethod, requestCallback, responseExtractor) – execute the httpMethod to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.

3.1. REST APIs to Consume

@Autowired
UserService userService;

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

	return new ResponseEntity<>(userService.getAll(), HttpStatus.OK);
}

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

	Optional<User> user = userService.getById(id);
	if (user.isPresent()) {
		return new ResponseEntity<>(user.get(), HttpStatus.OK);
	} else {
		throw new RecordNotFoundException();
	}
}

3.2. Consuming Response as String

We are fetching the API response as a JSON string in the given example. We need to use ObjectMapper to parse it to the POJO before using it in the application.

The getForObject() method is pretty useful when we are getting an unparsable response from the server, and we have no control to get it fixed on the server-side. Here, we can get the response as String, and use a custom parser or use a string replacement function to fix the response before handing it over to the parser.

private final String URI_USERS_ID = "/users/{id}";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

//Parse the string after getting the response
String userStr = restTemplate.getForObject(URI_USERS_ID, String.class, params);

Read More: Converting JSON String to Object using Jackson 2

3.3. Consuming Response to POJO

We are fetching the API response directly into the domain object in the given example.

3.3.1. Using getForObject() Method

private final String URI_USERS = "/users";
private final String URI_USERS_ID = "/users/{id}";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

// "users"
User[] usersArray = restTemplate.getForObject(URI_USERS, User[].class);

// "users/{id}"
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

User user = restTemplate.getForObject(URI_USERS_ID, User.class, params);

3.3.2. Using getForEntity() Method

private final String URI_USERS = "/users";
private final String URI_USERS_ID = "/users/{id}";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

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

// "users/{id}"
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

ResponseEntity<User> responseEntity = restTemplate
    .getForEntity(URI_USERS_ID, User.class, params);

3.4. Sending HTTP Headers

private final String URI_USERS = "/users";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

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(URI_USERS, HttpMethod.GET, entity, User[].class);

3.5. Sending URL Parameters

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

ResponseEntity<User> responseEntity = restTemplate
	.getForEntity(URI_USERS_ID, User.class, params);

4. Spring RestTemplate – HTTP POST Example

Available methods for consuming POST APIs are:

  • postForObject(url, request, classType) – POSTs the given object to the URL, and returns the representation found in the response as given class type.
  • postForEntity(url, request, responseType) – POSTs the given object to the URL, and returns the response as ResponseEntity.
  • postForLocation(url, request, responseType) – POSTs the given object to the URL, and returns returns the value of the Location header.
  • exchange(url, requestEntity, responseType)
  • execute(url, httpMethod, requestCallback, responseExtractor)

4.1. REST API to Consume

The POST API, we will consume in this example.

@PostMapping("users")
public ResponseEntity<User> create(@RequestBody User newUser) {

	User user = userService.save(newUser);
	if (user == null) {
		throw new ServerException();
	} else {
		return new ResponseEntity<>(user, HttpStatus.CREATED);
	}
}

4.2. Consuming a POST API

Spring REST client using RestTemplate to access HTTP POST api requests.

private final String URI_USERS = "/users";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

User newUser = new User(1, "Alex", "Golan", "a@mail.com");
User createdUser = restTemplate.postForObject(URI_USERS, newUser, User.class);
//Use the object as needed

5. Spring RestTemplate – HTTP PUT Method Example

Available methods are:

  • put(url, request) – PUTs the given request object to URL.

5.1. REST API to Consume

@PutMapping("users/{id}")
public ResponseEntity<User> update(@RequestBody User updatedUser) {

	User user = userService.save(updatedUser);
	if (user == null) {
		throw new ServerException();
	} else {
		return new ResponseEntity<>(user, HttpStatus.OK);
	}
}

5.2. Consuming a PUT API

private final String URI_USERS_ID = "/users/{id}";

@Autowired
RestTemplate restTemplate;

//Using RestTemplate

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

User updatedUser = new User(1, "Alex", "Golan", "a@mail.com");
User user = restTemplate.put(URI_USERS_ID, updatedUser, User.class);
//Use the object as needed

6. Spring RestTemplate – HTTP DELETE Method Example

Available methods are:

  • delete(url) – deletes the resource at the specified URL.

6.1. REST API to Consume

@DeleteMapping("users/{id}")
public HttpStatus delete(@PathVariable long id) {

	try {
		userService.delete(id);
		return HttpStatus.OK;
	} catch (Exception e) {
		throw new RecordNotFoundException();
	}
}

6.2. Consuming a DELETE API

private final String URI_USERS_ID = "/users/{id}";

@Autowired
RestTemplate restTemplate;

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

//Using RestTemplate

restTemplate.delete ( URI_USERS_ID,  params );

Feel free to copy and modify the above Spring RestTemplate examples for building the Spring REST API Consumer in your Spring WebMVC application.

7. RestTemplate Examples

Happy Learning !!

Sourcecode on Github

Leave a Reply

11 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