HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Boot 2 / Spring Boot RestTemplate / RestTemplate Example

Spring RestTemplate

After learning to build Spring REST API for XML representation and JSON representation, lets learn to build Spring REST client using the Spring RestTemplate to consume the APIs which we have written in 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 class

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 that is 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. Building RestTemplate Bean

The given below are few examples to create RestTemplate bean in the application. We are only looking at very simple bean definitions. For extensive configuration options, please refer to RestTemplate Configuration with HttpClient.

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

2.3. Using Apache HTTPClient

@Autowired
CloseableHttpClient httpClient;

@Bean
public RestTemplate restTemplate() {

    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
    return restTemplate;
}

@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {

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

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 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(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. HTTP GET REST APIs

@GetMapping(value = "/employees", 
		produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public EmployeeListVO getAllEmployees(
		@RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
        @RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation) 
{
	LOGGER.info("Header X-COM-PERSIST :: " + headerPersist);
	LOGGER.info("Header X-COM-LOCATION :: " + headerLocation);
	
    EmployeeListVO employees = getEmployeeList();
    return employees;
}

@GetMapping(value = "/employees/{id}", 
		produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") Integer id) 
{
	LOGGER.info("Requested employee id :: " + id);
	
    if (id != null && id > 0) {
    	//TODO: Fetch the employee and return from here
        EmployeeVO employee = new EmployeeVO(id, "Lokesh","Gupta", "howtodoinjava@gmail.com");
        return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
    }
    return new ResponseEntity<EmployeeVO>(HttpStatus.NOT_FOUND);
}

3.2. Spring RestTemplate example to consume REST API

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

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 handling it to the parser.

private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";

	//TODO: Autowire the RestTemplate in all the examples
	RestTemplate restTemplate = new RestTemplate();

	String result = restTemplate.getForObject(uri, String.class);
	System.out.println(result);
}

Read More: Converting JSON String to Object using Jackson 2

3.3. Spring RestTemplate example to consume API response into POJO

In the given example, we are fetching the API response directly into the domain object.

Using getForObject() Method

private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";
	RestTemplate restTemplate = new RestTemplate();
	
	EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class);
	
	//Use the response
}

Using getForEntity() Method

private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";
	RestTemplate restTemplate = new RestTemplate();

	ResponseEntity<EmployeeListVO> response = restTemplate.getForEntity(uri, EmployeeListVO.class);

	//Use the response.getBody()
}

3.4. Sending HTTP Headers using RestTemplate

private static void getEmployees()
{
	final String uri = "http://localhost:8080/springrestexample/employees";
	RestTemplate restTemplate = new 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<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
	
	//Use the response.getBody()
}

3.5. Sending URL Parameters using RestTemplate

private static void getEmployeeById()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";
	RestTemplate restTemplate = new RestTemplate();
	
	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "1");
	
	EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params);
	
	//Use the result
}

4. Spring RestTemplate – HTTP POST Example

Available methods 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. HTTP POST REST API

The POST API, we will consume in this example.

@PostMapping(value = "/employees")
public ResponseEntity<String> createEmployee(EmployeeVO employee) 
{
	//TODO: Save employee details which will generate the employee id
	employee.setId(111);
	
	//Build URI
	 URI location = ServletUriComponentsBuilder.fromCurrentRequest()
		                 .path("/{id}")
		                 .buildAndExpand(employee.getId())
		                 .toUri();
    return ResponseEntity.created(location).build();
}

4.2. Spring RestTemplate example to consume POST API

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

private static void createEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees";
	RestTemplate restTemplate = new RestTemplate();

	EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly", "test@email.com");
	
	EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);

	System.out.println(result);
}

5. Spring RestTemplate – HTTP PUT Method Example

Available methods are:

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

5.1. HTTP PUT REST API

@PutMapping(value = "/employees/{id}")
public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id") int id
				,EmployeeVO employee) 
{
	//TODO: Save employee details
    return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
}

5.2. Spring RestTemplate example to consume PUT API

private static void updateEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";
	RestTemplate restTemplate = new RestTemplate();
	
	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "2");
	
	EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly", "test@email.com");
	
	restTemplate.put ( uri, updatedEmployee, params );
}

6. Spring RestTemplate – HTTP DELETE Method Example

Available methods are:

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

6.1. HTTP DELETE REST API

@DeleteMapping(value = "/employees/{id}")
public ResponseEntity<String> deleteEmployee(@PathVariable("id") int id) 
{
	//TODO: Delete the employee record
    return new ResponseEntity<String>(HttpStatus.OK);
}

6.2. Spring RestTemplate example to consume DELETE API

private static void deleteEmployee()
{
	final String uri = "http://localhost:8080/springrestexample/employees/{id}";
	RestTemplate restTemplate = new RestTemplate();
	
	Map<String, String> params = new HashMap<String, String>();
	params.put("id", "2");
	
	restTemplate.delete ( uri,  params );
}

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

7. RestTemplate Examples

Spring RestTemplate basic authentication example
Spring RestTemplate timeout configuration example
Spring RestTemplateBuilder Example
Spring RestTemplate – HttpClient configuration example
Spring Boot RestTemplate GET Example
Spring Boot RestTemplate POST Example
Spring boot JUnit example with RestTemplate
Spring boot TestRestTemplate POST with headers example
Spring ClientHttpRequestInterceptor with RestTemplate

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Baljinder Singh

    February 25, 2020

    Hi , I was hitting url , What i noticed is that i am not getting response body in restTemplate.exchange -post method. But the same data i am passing through postman , i am able to get response body. Can you give any suggestion on what could be the reason. Note that i have double checked all data headers, content Type(“application/x-www-form-urlencoded”) is same.

  2. Vinni

    February 3, 2020

    Hi,

    RestTemplate usage is explained only for endpoint URI with the default port (8080). Will there be any changes if I want to use RestTemplate for a URI with a specific port (Ex: 4433)?. Thanks in advance.

    Regards,
    Vinni

  3. Bala Kajendran

    April 8, 2019

    Please kindly post that how to consume from https rest service.

  4. Deep Lathia

    February 11, 2019

    Hi,

    I am trying to call a third party api gateway from my server using RestTemplate. I am able to make an successful request through Postman on the third party api gateway but when i try to do that using my code, it’s throwing an exception that i am unable to solve. Please have a look at the below link. Any leads will be appreciated

    https://stackoverflow.com/questions/54429549/spring-boot-multipart-content-type-http-request-using-resttemplate

    Regards,
    Deep

  5. zaikanhai5

    May 23, 2018

    How to use RestTemplate for download file by redirect ? tks!

  6. Blue

    December 3, 2017

    Most of REST Client tools do not support automated testing.

    Once used a tool called WisdomTool REST Client supports automated testing, output exquisite report, and automatically generating RESTful API document.

    Lightweight tool with very powerful features!

    https://github.com/wisdomtool/rest-client

  7. Ajit

    August 5, 2017

    Hi,
    Could u also post example of post object with files.

  8. codemon2002

    May 3, 2017

    Hi Lokesh,

    I tried using the restTemplate.postforobject(uriString,employeeJsonString,String.class). I know the json I am passing in is working because I can use swagger and get successes, but when I use RestTemplate, I am getting 415 error media type. So is there something I need to inject or setup with the RestTemplate before I can run it? I am a bit new to Spring APIs so I totally understand if I am missing something basic. Thanks!

  9. Shubham Goel

    December 3, 2016

    Not a good tutorial. You have just pasted the code. No explanation or description.

    • Lokesh Gupta

      December 3, 2016

      I will put explanation in future. Thanks for feedback.

  10. Jeevan Sunkersett

    November 13, 2016

    Hi Lokesh,

    Your tutorial is very informative.

    But I want to consume REST services, which are behind a API Gateway and over a HTTPS protocol (secure) – they have been developed by my client – and he said that he will provide the required client certificates as well.

    Please can you include this aspect in your tutorial

    thank you
    Jeevan

  11. Ritesh

    October 4, 2016

    Hi Lokesh,

    Your tutorials are really very helpful……Can you please let me know how can we use OAuth 2.0 in Spring Security.

    • Lokesh Gupta

      October 4, 2016

      I will write a detailed tutorial on oauth 2 very soon.

  12. Neeraj

    October 1, 2016

    Hi Lokesh,

    I am developing spring application. In application i have created rest api as below

    @Controller
    @RequestMapping("api/users")
    public class UserController {
    
    	User user = new User();
    	@RequestMapping(value ="{name}", method = RequestMethod.GET, produces = "application/json")
    	public @ResponseBody User getUserDetails(@PathVariable String name) {
    		user.setName(name);
    		user.setAge(26);
    		return user;
    	}
    }
    

    When i have deploy my application in jetty server. its scans my controller

    INFO: Mapped “{[/api/users/{name}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}”

    But whenever i am trying to access this url by passing name parameter I am getting 404 Error. Please suggest what could be the problem. I have tried all possible ways.

    Thanks,
    Neeraj Goyal

    • Lokesh Gupta

      October 1, 2016

      Are you able to hit the root URL of our application i.e. “/”.

  13. Sowmya

    July 30, 2016

    Hi Lokesh,

    Your tutorials are very nice and I follow them regularly.
    I have an issue that when I access your site from my iPad, the right most part of code samples is getting truncated and there is no scroll bar to view the entire line. Can you please verify this on iPad and adjust the width of the frames accordingly ?
    Thanks

    • Sowmya

      July 30, 2016

      Lokesh,
      please ignore my earlier comment and scrolling is working for me ?.
      Also, in PUT method Rest client code, you meant to name the method as updateEmployee() right? Using deleteEmployee() was little confusing.

      Very good explanation of this concept though.

  14. Syed Wahed Hussain

    June 17, 2016

    How can I call a Restful webservice through a Spring client when the actual webservice is developed in Jersey framework.
    I am specifically looking to call post webservice through a Json object as input.

  15. murali

    February 29, 2016

    hi , thanks for the providing the information, if suppose i want to provide the security to the web service,how it can be possible ???

  16. miral

    February 28, 2016

    How to consume response body in case of response code like 401. Lets say I made call with resttemplate and it returned 401 and response contains body with reason …right now its throwing exception – HttpClientErrorException – and http converters are no executed…

  17. alessio

    December 21, 2015

    For GET, Under section “3) Using custom HTTP Headers with RestTemplate”

    Your code shows:

    ResponseEntity result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);

    Shouldn’t be?:

    ResponseEntity result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

    • Lokesh Gupta

      December 22, 2015

      Yeh !! It should be. Typo Mistake, corrected it.

  18. Karthik PV

    September 29, 2015

    Hi, Does Spring RestTemplate support DELETE with Body?

    • Lokesh Gupta

      September 29, 2015

      No, entity body is not supported for DELETE requests.

  19. Leena

    April 22, 2015

    How we can add OAuth token in Header while calling GET for

    restTemplate.getForObject(uri, EmployeeListVO.class);

    Please reply ASAP

    • Lokesh Gupta

      April 22, 2015

      Look around this: OAuth2RestTemplate and https://stackoverflow.com/questions/27864295/how-to-use-oauth2resttemplate

  20. Neha Sharma

    April 19, 2015

    Hi Lokesh, I’m looking forward to implement the Spring OAuth2 example using OAuth2RestTemplate. I goggled lot to find the solution, but did not find any working example. Finally I got the URL (which is very nice)
    https://stackoverflow.com/questions/23486186/access-tokens-using-2-legged-oauth-2-0-and-apache-oauthclient. I’m trying to implement the solution-2, but not sure how we can integrate with Facebook + Spring OAuth2 using rest template. Could you please help me ASAP ?

    Thanks,
    Neha Sharma

    • Neha Sharma

      April 21, 2015

      Hi Lokesh – Would you like to give any suugestions on above question?
      Thanks,
      Neha Sharma

      • Lokesh Gupta

        April 21, 2015

        As of now, I am also not aware of how it should be done. I will try.

  21. Binh Thanh Nguyen

    March 6, 2015

    Thanks, nice post

Comments are closed on this article!

Search Tutorials

Spring Boot RestTemplate

  • RestTemplate Introduction
  • RestTemplate Builder
  • RestTemplate with HttpClient
  • RestTemplate GET Example
  • RestTemplate POST Example
  • RestTemplate Basic Auth
  • RestTemplate Timeout
  • ClientHttpRequestInterceptor

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)