Spring RestTemplate (with Examples)
Spring RestTemplate is a synchronous REST client performing HTTP requests using a simple template-style API. It uses an underlying HTTP client library, such as JDK HttpURLConnection, Apache HttpComponents etc. 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.
Depreciation Warning: Spring docs recommend to use the non-blocking, reactive WebClient API which offers efficient support for both sync, async and streaming scenarios. RestTemplate will be deprecated in the future versions.
Given that the RestTemplate class is a synchronous client and 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.
Include the latest version of spring-web dependency to use RestTemplate in the application.
org.springframework spring-web 6.0.2
If you are using Spring boot then we can import all necessary dependencies by including the spring-boot-starter-web dependency.
org.springframework.boot spring-boot-starter-web 3.0.0
2. Creating Spring RestTemplate Instance
The given below are a few ways to create RestTemplate bean in the application.
The simplest way to create a RestTemplate instance is by using its constructor:
RestTemplate restTemplate = new RestTemplate();
2.2. Using RestTemplateBuilder
The builder offers to customize the advanced configurations such as timeouts.
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder)
2.3. Using SimpleClientHttpRequestFactory
It uses standard JDK facilities to create a factory for new ClientHttpRequest objects.
@Bean public RestTemplate restTemplate()
2.4. Using Apache HTTPClient (Recommended)
Apache HTTP client library provides a very granular level of control for whole request and response processing. We can use its CloseableHttpClient as the implementation of HttpClient that also implements Closeable .
@Autowired CloseableHttpClient httpClient; @Value("$") private String apiHost; @Bean public RestTemplate restTemplate() < RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost)); return restTemplate; >@Bean @ConditionalOnMissingBean public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory()
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 the 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, prepare the request with the RequestCallback, and read the response with a ResponseExtractor.
We have the following two GET APIs that we will learn to consume using the RestTemplate.
@GetMapping("users") public ResponseEntity> getAll() < . >@GetMapping("users/") public ResponseEntity getById(@PathVariable long id)
3.1. API Response as JSON String
The getForObject() is pretty useful when we are getting an unparsable response from the server, and we have no control over getting 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.
String userJson = restTemplate.getForObject("/users/", String.class, Map.of("id", "1"));
We can use the getForEntity() API which returns the ResponseEntity instance. To extract the response body, use its responseEntity.getBody() method.
ResponseEntity responseEntity = restTemplate.getForEntity("/users/", String.class, Map.of("id", "1")); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(responseEntity.getBody());
We can fetch the API response directly into the domain object using the getForObject() API.
User[] usersArray = restTemplate.getForObject("/users", User[].class); User user = restTemplate.getForObject("/users/", User.class, Map.of("id", "1"));
Similarly, getForEntity() API can be used to fetch the ResponseEntity object.
ResponseEntity responseEntity = restTemplate.getForEntity("/users", User[].class); ResponseEntity responseEntityUser = restTemplate.getForEntity("/users/", User.class, Map.of("id", "1"));
If we want to send the request headers then we need to use the generic exchange() API.
HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("X-COM-PERSIST", "NO"); headers.set("X-COM-LOCATION", "USA"); HttpEntity entity = new HttpEntity(headers); ResponseEntity responseEntity = restTemplate.exchange("/users", HttpMethod.GET, entity, User[].class);
The 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 the value of the Location header.
- exchange(url, requestEntity, responseType)
- execute(url, httpMethod, requestCallback, responseExtractor)
We will consume the following POST API using the RestTemplate:
@PostMapping("users") public ResponseEntity create(@RequestBody User newUser)
The postForObject() API accepts a POJO instance directly submitted to the remote API and can return the response body having the created resource.
User newUser = new User(1, "Alex", "Golan", "alex@mail.com"); //POJO User createdUser = restTemplate.postForObject("/users", newUser, User.class);
The postForLocation() API is very similar to postForObject(), except it returns only the Location of the created resource.
User newUser = new User(1, "Alex", "Golan", "alex@mail.com"); URI location = restTemplate.postForLocation("/users", newUser, User.class);
The available method to invoke an HTTP PUT API is:
We are consuming the following PUT API.
@PutMapping("users/") public ResponseEntity update(@RequestBody User updatedUser)
Use the put() API as follows:
User user = new User(1, "Alex", "Golan", "a@mail.com"); //POJO User updatedUser = restTemplate.put("/users/", user, User.class, Map.of("id", "1"));
The available methods for invoking an HTTP DELETE API are:
We are consuming the following DELETE API.
@DeleteMapping("users/") public HttpStatus delete(@PathVariable long id)
Use the delete() API as follows:
restTemplate.delete ("/users/", Map.of("id", "1"));
Feel free to copy and modify the above Spring RestTemplate examples for building the Spring REST API Consumer in your Spring WebMVC application.
Spring RestTemplate Example
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Spring RestTemplate
- Spring RestTemplate class is part of spring-web , introduced in Spring 3.
- We can use RestTemplate to test HTTP based restful web services, it doesn’t support HTTPS protocol.
- RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE etc.
Spring RestTemplate Example
URI | HTTP Method | Description |
---|---|---|
/springData/person | GET | Get all persons from database |
/springData/person/ | GET | Get person by id |
/springData/person | POST | Add person to database |
/springData/person | PUT | Update person |
/springData/person/ | DELETE | Delete person by id |
Let’s start creating our Rest client project to test these web services. Below image shows our final Spring RestTemplate example project.
Spring RestTemplate Maven Dependencies
We need spring-core , spring-context dependencies for spring framework. Then we need spring-web artefact that contains RestTemplate class. We also need jackson-mapper-asl for Spring JSON support through Jackson API.
4.0.0 com.journaldev.spring SpringRestTemplate 1.0-SNAPSHOT 4.3.0.RELEASE 3.0.2.RELEASE 2.8.1 org.springframework spring-core $ org.springframework spring-context $ org.codehaus.jackson jackson-mapper-asl 1.9.4 org.springframework spring-web $
Spring Configuration Class
We have to define a spring bean for RestTemplate class, that’s done in AppConfig class.
package com.journaldev.spring.config; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.web.client.RestTemplate; @Configuration @ComponentScan("com.journaldev.spring") public class AppConfig < @Bean RestTemplate restTemplate() < RestTemplate restTemplate = new RestTemplate(); MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); converter.setObjectMapper(new ObjectMapper()); restTemplate.getMessageConverters().add(converter); return restTemplate; >>
Note that RestTamplate uses MessageConverter and we need to set this property in the RestTemplate bean. In our example we are using MappingJacksonHttpMessageConverter for fetching data from JSON format.
Model Class
Since we are trying to convert JSON returned by our web service to a java object using jackson mapper, we have to create the model class for this. Note that this model class will be very similar to the model class used in the web service, except that here we don’t need JPA annotations.
package com.journaldev.spring.model; public class Person < private Long id; private Integer age; private String firstName; private String lastName; public Person() < >public Long getId() < return id; >public void setId(Long id) < this.id = id; >public Integer getAge() < return age; >public void setAge(Integer age) < this.age = age; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >@Override public String toString() < return "Person'; > >
Spring RestTemplate Client Class
Final step is to create the client classes that will use RestTemplate bean defined above.
package com.journaldev.spring.config; import java.util.List; import org.springframework.http.HttpStatus; import com.journaldev.spring.model.Person; public interface PersonClient < ListgetAllPerson(); Person getById(Long id); HttpStatus addPerson(Person person); void updatePerson(Person person); void deletePerson(Long id); >
package com.journaldev.spring.config; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.journaldev.spring.model.Person; @Service public class PersonClientImpl implements PersonClient < @Autowired RestTemplate restTemplate; final String ROOT_URI = "https://localhost:8080/springData/person"; public ListgetAllPerson() < ResponseEntityresponse = restTemplate.getForEntity(ROOT_URI, Person[].class); return Arrays.asList(response.getBody()); > public Person getById(Long id) < ResponseEntityresponse = restTemplate.getForEntity(ROOT_URI + "/"+id, Person.class); return response.getBody(); > public HttpStatus addPerson(Person person) < ResponseEntityresponse = restTemplate.postForEntity(ROOT_URI, person, HttpStatus.class); return response.getBody(); > public void updatePerson(Person person) < restTemplate.put(ROOT_URI, person); >public void deletePerson(Long id) < restTemplate.delete(ROOT_URI + id); >>
The code is self understood, we are calling RestTemplate methods based on the URI and the HTTP method and by passing appropriate request object if needed.
Spring RestTemplate Test Class
It’s time to test our Spring RestTemplate example project, below class shows how to use RestTemplate methods in Spring way.
package com.journaldev.spring; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.http.HttpStatus; import com.journaldev.spring.config.AppConfig; import com.journaldev.spring.config.PersonClient; import com.journaldev.spring.model.Person; public class Main < public static void main(String[] args) < AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); PersonClient client = applicationContext.getBean(PersonClient.class); System.out.println("Getting list of all people:"); for (Person p : client.getAllPerson()) < System.out.println(p); >System.out.println("\nGetting person with ID 2"); Person personById = client.getById(2L); System.out.println(personById); System.out.println("Adding a Person"); Person p = new Person(); p.setAge(50); p.setFirstName("David"); p.setLastName("Blain"); HttpStatus status = client.addPerson(p); System.out.println("Add Person Response = " + status); applicationContext.close(); > >
When I run above program against my local setup, I get following output.
Getting list of all people: Person Person Getting person with ID 2 Person Adding a Person Add Person Response = 201
Below image shows the web service database table data before and after executing above program. As you can see that the program output matches with the sample table data. That’s all for Spring RestTemplate example, you can download the project from below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.