Spring RestTemplate

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

Table of Contents

1. Spring RestTemplate class
2. Building RestTemplate Bean
3. HTTP GET Example
4. HTTP POST Example
5. HTTP PUT Example
6. HTTP DELETE Example
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 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);
}

2.3. Using Apache HTTPClient (Recommended)

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

@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 REST APIs as String

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 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 REST API response to POJO

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

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 using RestTemplate

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 using RestTemplate

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

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. Spring RestTemplate example to consume 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. HTTP PUT REST API

@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. Spring RestTemplate example to consume 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. HTTP DELETE REST API

@DeleteMapping("users/{id}")
public HttpStatus delete(@PathVariable long id) {
	try {
		userService.delete(id);
		return HttpStatus.OK;
	} catch (Exception e) {
		throw new RecordNotFoundException();
	}
}

6.2. Spring RestTemplate example to consume 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 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?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

24 thoughts on “Spring RestTemplate”

  1. 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.

    Reply
  2. 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

    Reply
  3. 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

    Reply
  4. 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!

    Reply
  5. 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

    Reply
  6. 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

    Reply
  7. 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

    Reply
    • 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.

      Reply
  8. 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.

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

    Reply
  10. 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…

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

    restTemplate.getForObject(uri, EmployeeListVO.class);

    Please reply ASAP

    Reply
  12. 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

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.