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.
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); }
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 !!
Baljinder Singh
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.
Vinni
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
Bala Kajendran
Please kindly post that how to consume from https rest service.
Deep Lathia
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
zaikanhai5
How to use RestTemplate for download file by redirect ? tks!
Blue
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
Ajit
Hi,
Could u also post example of post object with files.
codemon2002
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!
Shubham Goel
Not a good tutorial. You have just pasted the code. No explanation or description.
Lokesh Gupta
I will put explanation in future. Thanks for feedback.
Jeevan Sunkersett
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
Ritesh
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
I will write a detailed tutorial on oauth 2 very soon.
Neeraj
Hi Lokesh,
I am developing spring application. In application i have created rest api as below
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
Are you able to hit the root URL of our application i.e. “/”.
Sowmya
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
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.
Syed Wahed Hussain
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.
murali
hi , thanks for the providing the information, if suppose i want to provide the security to the web service,how it can be possible ???
miral
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…
alessio
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
Yeh !! It should be. Typo Mistake, corrected it.
Karthik PV
Hi, Does Spring RestTemplate support DELETE with Body?
Lokesh Gupta
No, entity body is not supported for DELETE requests.
Leena
How we can add OAuth token in Header while calling GET for
restTemplate.getForObject(uri, EmployeeListVO.class);
Please reply ASAP
Lokesh Gupta
Look around this: OAuth2RestTemplate and https://stackoverflow.com/questions/27864295/how-to-use-oauth2resttemplate
Neha Sharma
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
Hi Lokesh – Would you like to give any suugestions on above question?
Thanks,
Neha Sharma
Lokesh Gupta
As of now, I am also not aware of how it should be done. I will try.
Binh Thanh Nguyen
Thanks, nice post