Spring Boot – Rest Template
Last Updated :
23 Oct, 2023
RestTemplate is a powerful synchronous client for handling HTTP communication in Spring Boot applications. It internally uses an HTTP client library i.e. java.net.HttpURLConnection, simplifying the process of making RESTful requests to external services and APIs, including convenience, along with integration, and flexibility for various HTTP communication. Overall in this article, we will see how to invoke external APIs using methods provided by RestTemplate in your Spring Boot Application. RestTemplate is a well-known rest client in the Spring framework to performs synchronous HTTP requests.
What are the Benefits of Using the RestTemplate?
RestTemplate in Spring Boot offers simplified HTTP request handling, seamless Spring integration, inter-service communication, customization, error handling, and ease of use. It also supports authentication, making it versatile for various API interactions.
getForEntity(), getForObject()
|
postForObject()
|
put()
|
delete()
|
Note: To carry out any of the aforementioned operations, use exchange().
Configuring the RestTemplate
All the packages/libraries for RestTemplate are present in spring-boot-starter-web which comes under org.springframework.web
XML
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-web</ artifactId >
</ dependency >
|
You must define @Bean of RestTemplate in Spring Boot Configuration.
Java
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
|
Note: While declaring the RestTemplate @Bean in separate config class Its important to annotate the class with @Configuration, then only @Bean gets recognised by Spring boot Application.
Creating a RestTemplate Instance
In the class where you want to use RestTemplate methods, it is important to Inject the RestTemplate instance using @Autowired annotation, to make seamless HTTP requests.
Java
@Autowired
private RestTemplate restTemplate;
|
Common HTTP Operations
GET Request
There are 3 methods available in RestTemplate for GET Requests, which are getForObject, getForEntity, and exchange.
- getForObject should be used when you have an exact declaration of Java class for the same, so that the response automatically converts it to a Java object, making it convenient for straightforward use cases.
- getForEntity returns the response encapsulated into a ResponseEntity Object. It also contains HTTP status codes and headers, allowing more control over the handling of the data. Provides more flexibility over getForObject.
- exchange is the most advanced and widely used for GET requests. Using it you can access the full range of response information, including status code, headers, and the response body. Best suitable when you need to customize the request headers or non-standard response types.
Java
@GetMapping ( "/getForObject/allEmployees" )
public ResponseEntity<?> getCustomersUsingGetForObject()
{
Customer[] CustomerData = restTemplate.getForObject(
URI_CUSTOMER, Customer[]. class );
return new ResponseEntity<>(Arrays.asList(CustomerData),
HttpStatus.OK);
}
@GetMapping ( "/getForEntity/allEmployees" )
public ResponseEntity<?> getCustomersUsingGetForEntity()
{
ResponseEntity<Customer[]> responseEntity
= restTemplate.getForEntity(URI_CUSTOMER,
Customer[]. class );
return responseEntity;
}
@GetMapping ( "/exchange/allEmployees" )
public ResponseEntity<?> getCustomersUsingExchange()
{
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(
MediaType.APPLICATION_JSON));
HttpEntity<String> entity
= new HttpEntity<>(httpHeaders);
return restTemplate.exchange(URI_CUSTOMER,
HttpMethod.GET, entity,
Customer[]. class );
}
|
POST Request
There are two methods to call any POST API using RestTemplate, which are exchange, and postForObject.
- postForObject: It receives a response as an object. Mainly it accepts URL, request entity, and response class type as parameters making it a straightforward and easy option.
- exchange: It offers greater flexibility by allowing various customization in request and response. It accepts an HTTP method, URL, request entity, and response type as parameters, making it suitable for complex cases.
Java
@PostMapping ( "/postForObject/customer" )
public ResponseEntity<?>
addCustomerUsingPostForObject( @RequestBody Customer)
{
Customer createdCustomer = restTemplate.postForObject(
URI_CUSTOMER, newCustomer, Customer. class );
return new ResponseEntity(createdCustomer,
HttpStatus.CREATED);
}
@PostMapping ( "/exchange/customer" )
public ResponseEntity
addCustomerUsingExchange( @RequestBody Customer newEmployee)
{
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(
MediaType.APPLICATION_JSON));
HttpEntity<Customer> entity
= new HttpEntity<>(newEmployee, httpHeaders);
return restTemplate.exchange(URI_CUSTOMER,
HttpMethod.POST, entity,
Customer. class );
}
|
PUT Request
There are 2 methods available in RestTemplate for PUT Requests, which are put, and exchange.
- put: It allows to update/replace a resource on the server by specifying the URL and updated Data. No extra configuration or custom handling is required.
- exchange: you can customize headers, set request parameters, and extract detailed information from the HTTP response, making it suitable for complex scenarios and advanced use cases.
Java
@PutMapping ( "/put/customer/{id}" )
public ResponseEntity<?> updateCustomerUsingPut(
@PathVariable Integer id,
@RequestBody Customer newEmployee){
Map<String, String> params = new HashMap<>();
params.put( "id" , String.valueOf(id));
restTemplate.put(URI_CUSTOMER_ID, newEmployee, params);
return new ResponseEntity(
"Customer Updated with id " + id, HttpStatus.OK);
}
@PutMapping ( "/exchange/customer/{id}" )
public ResponseEntity<?> updateCustomerUsingExchange(
@PathVariable Integer id,
@RequestBody Customer newEmployee){
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(
MediaType.APPLICATION_JSON));
HttpEntity<Customer> entity
= new HttpEntity<>(newEmployee, httpHeaders);
return restTemplate.exchange(URI_CUSTOMER + id,
HttpMethod.PUT, entity,
Customer. class );
}
|
DELETE Request
There are 2 methods available in RestTemplate for DELETE Requests, which are delete, and exchange.
- delete: a simple way to send an HTTP DELETE request. It accepts a URL and URI variable (Optional) for requests. No customization is required.
- exchange: while handling authentication or working with APIs that require custom headers exchange is the best choice.
Java
@DeleteMapping ( "/delete/customer/{id}" )
public ResponseEntity deleteCustomerUsingDelete(
@PathVariable Integer id){
Map<String, String> params = new HashMap<>();
params.put( "id" , String.valueOf(id));
restTemplate.delete(URI_CUSTOMER_ID, params);
return new ResponseEntity<>(
"Customer deleted with id " + id, HttpStatus.OK);
}
@DeleteMapping ( "/exchange/customer/{id}" )
public ResponseEntity<Customer> deleteCustomerUsingExchange(
@PathVariable Integer id){
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(
MediaType.APPLICATION_JSON));
HttpEntity<Customer> entity
= new HttpEntity<>(httpHeaders);
return restTemplate.exchange(URI_CUSTOMER + id,
HttpMethod.DELETE, entity,
Customer. class );
}
|
Notes:
Error Handling in RestTemplate
Handling HTTP Errors with the RestTemplate
While making an API call make sure to use error handling
Java
@GetMapping ( "/getForObject/allEmployees" )
public ResponseEntity getAllCustomer(){
try {
Customer[] CustomerData = restTemplate.getForObject(
URI_CUSTOMER, Customer[]. class );
return new ResponseEntity<>(
Arrays.asList(CustomerData), HttpStatus.OK);
}
catch (HttpClientErrorException
| HttpServerErrorException ex) {
}
return null ;
}
|
Custom Error Handling
Declare your own custom error response form to handle Custom Error Handling.
Share your thoughts in the comments
Please Login to comment...