10 Examples of RestTemplate in Spring Framework

Hello guys, if you are wondering how to send GET and POST request to your API or Web Service from a Java based Spring Framework then you would be glad to know that You can use use RestTemplate class from Spring Framework. It's a fully functional HTTP client which is really really useful in this age of API. I have used RestTemplate to consume JSON from API before as well as sending different kind of request like POST, PUT, DELETE and PATCH to any REST API. For example, in this article, I shared how to send POST request using RestTemplate and how to set header on HTTP request using RestTemplate. Yes, RestTemplate also allow you to send headers like Authorization on Http Request. 

For a long time this was my go-to HTTP client as back then Java didn't have any thing like that and most project we worked used Spring. But, now, you can also use new HttpClient class from Java 11 as well as new WebClient class from Spring Boot to make REST API calls but nevertheless, this class is still quite important and in this article, I will show you how to use RestTemplate effectively in Java. 

But, , Before we get to the 10 best examples that will teach you everything there is to know about the RestTemplate in Spring, let me tell you a little bit more about what it really is.


10 Examples Of RestTemplate In Spring

In Spring, the RestTemplate is basically a class that is designed according to the same principles as the many other Spring Template classes like JdbcTemplate and JmsTemplate. It will provide you a very simplified approach along with some default behaviors that can be used for performing complex tasks. 

The RestTemplate class is actually a synchronous client that is designed to call REST services. Therefore, its primary methods are also closely related to REST's underpinnings. 

You will eventually get used to the HTTP protocol methods like HEAD, GET, DELETE, PUT, POST, and OPTIONS.


10 Examples of RestTemplate class in Spring Framework



1. Building RestTemplate using RestTemplateBuilder

It is possible to build a RestTemplate bean using a variety of methods. Look at the example given below to see how you can use RestTemplateBuilder.

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

2. Building RestTemplate Using SimpleClientHttpRequestFactory

Another way to build RestTemplate is by making use of the SimpleClientHttpRequestFactory. See the following example:

public RestTemplate restTemplate() {
	var factory = new SimpleClientHttpRequestFactory();
	factory.setConnectTimeout(3000);
	factory.setReadTimeout(3000);
	return new RestTemplate(factory);
}



3. Building RestTemplate Using Apache HTTPClient

This is the most efficient and popular way to build RestTemplate in Spring. See the following example to get a better understanding:

@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;
}

4. How To Inject The RestTemplate Bean

You can inject the RestTemplate bean by making use of the popular @Autowired annotation. Using the @Qualifier annotation, you can also have multiple beans with different configurations. Look at the following example:

@Autowired
private RestTemplate restTemplate;

5. Consuming Responses (String)

You can fetch the API response in the form of a JSON string. You will need to use ObjectMapper and parse it to the POJO and then use it in the application. The getForObject() method can be really useful if you are looking to get an unparsable response from the server. 

You may also have no control to have it fixed on the control side. Therefore, you get the response as a string and use the custom parser or a string replacement function.

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);



6. Consuming Responses to POJO

Look at the following example to see how to fetch the API response directly into the domain object using the 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);

You can also use the getForEntity() method for performing the same task. 

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);



6. Sending HTTP Headers

Check out the following example to learn how you can send HTTP Headers with the RestTemplate in Spring:

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);

7. How to Send URL Parameters In Spring

You can use the following syntax for sending URL parameters in Spring:

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

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




8. Consuming A POST API 

You can also use the RestTemplate in Spring for accessing 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

9. How to Consume a PUT API

Here is an example of how to send a PUT request using RestTemplate class in a Java and Spring application:

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


10. How to Consume A DELETE API

Here is a code example to send a DELETE request to a REST API using Spring Framework's RestTemplate class in Java application

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 );


RestTemplate Frequently Asked Questions

1. What exactly is RestTemplate?

In Spring, the RestTemplate is basically a class that is designed according to the same principles as the many other Spring Template classes like JdbcTemplate and JmsTemplate. It will provide you a very simplified approach along with some default behaviors that can be used for performing complex tasks


2. What can I do with the RestTemplate?

The RestTemplate class is actually a synchronous client that is designed to call REST services. Therefore, its primary methods are also closely related to REST's underpinnings. You will eventually get used to the HTTP protocol methods like HEAD, GET, DELETE, PUT, POST, and OPTIONS. 

3. Is it possible to Autowire RestTemplate?

You cannot autowire the RestTemplate without specifying the particular bean configuration. 

Conclusion

That's all about how to use RestTemplate class in Spring Framework to call RESTful web services. This fully functional class allows you to send GET, POST, PUT, and DELETE request to any REST API. It also allows you to set headers, cookies as well request parameters. It's one of those handy classes which you will need everyday but with the introduction of HttpClient in Java 11, you will probably not need it any more for making HTTP request. 

There is also an alternative WebClient which can be used to send async HTTP request. As you can see, you can use the examples given in this list to understand the fundamentals of the RestTemplate in Spring. If you liked this list of 10 examples of the RestTemplate in Spring, feel free to share it with your friends and family.
 

Other Java REST Tutorials and Resources you may like
  • 7 Best Courses to learn Spring Framework (best courses)
  • How to create a REST client using the Spring framework in Java? (tutorial)
  • Top 5 Books to learn RESTful APIs and Web Services (books)
  • 10 Free Courses to learn Spring Boot (Free Courses)
  • My Favorite Courses to learn Software Architecture (courses)
  • Spring HelloWorld Example using Dependency Injection (tutorial)
  • How to convert a JSON array to a String array in Java? (tutorial)
  • Top 5 courses to learn GraphQL for Beginners (courses)
  • Top 10 REST Web Service Interview Questions (answer)
  • Top 5 Courses to learn RESTFul Web Services in Java? (courses)
  • Difference between Idempotent and safe methods in HTTP? (answer)
  • Difference between REST and SOAP Web Services? (answer)
  • How to create a JDBC connection pool using Spring? (tutorial)
  • Difference between PUT vs POST in REST Web Service? (article)
  • Top 10 Courses to learn Microservices for Java developers (courses)

Thanks for reading this article so far. If you like this tutorial of sending HTTP requests from the Java Program using RestTemplate then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

You can also post a comment if you have any doubts about any of the examples given in this list and we will get back to you as soon as possible. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.