Open In App

Spring Boot – Rest Template

Last Updated : 23 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Operation

Methods

GET

getForEntity(), getForObject()

POST

postForObject()

PUT

put()

DELETE

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 Configuration for RestTemplate
@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




// Injection of RestTemplate into class
@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.

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




// We have 3 methods available for a GET using
// RestTemplate in Spring Boot Application
 
 
@GetMapping("/getForObject/allEmployees")
public ResponseEntity<?> getCustomersUsingGetForObject()
{
 
    // Using getForObject method to fetch
    // Customer Data from URL and automatically
    // convert the response into array of customer
    Customer[] CustomerData = restTemplate.getForObject(
        URI_CUSTOMER, Customer[].class);
 
    // Returning a Response of 200 OK along with
    // Customer-Data wrapped into ResponseEntity
    return new ResponseEntity<>(Arrays.asList(CustomerData),
                                HttpStatus.OK);
}
 
@GetMapping("/getForEntity/allEmployees")
public ResponseEntity<?> getCustomersUsingGetForEntity()
{
 
    // Using getForEntity method to fetch
    // Customer Data from URL and automatically
    // recieve Customer-Data wrapped into ResponseEntity
    ResponseEntity<Customer[]> responseEntity
        = restTemplate.getForEntity(URI_CUSTOMER,
                                    Customer[].class);
 
    return responseEntity;
}
 
@GetMapping("/exchange/allEmployees")
public ResponseEntity<?> getCustomersUsingExchange()
{
 
    // Instantiate HttpHeaders to add custom properties.
    HttpHeaders httpHeaders = new HttpHeaders();
 
    // set the Accept-header as APPLICATION_JSON to get the
    // content in JSON format
    httpHeaders.setAccept(Collections.singletonList(
        MediaType.APPLICATION_JSON));
 
    // building a HttpEntity using HttpHeaders to
    // customize the request
    HttpEntity<String> entity
        = new HttpEntity<>(httpHeaders);
 
    // exchange method can be used for GET request with
    // cutomer headers. It returns Customer Data Wrapped
    // into ResponseEntity with response body, headers and
    // status
    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.

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




// We have 2 methods available for a POST using
// RestTemplate in Spring Boot Application
 
@PostMapping("/postForObject/customer")
public ResponseEntity<?>
addCustomerUsingPostForObject(@RequestBody Customer)
{
 
    // Sending post request to create a newCustomer using
    // postForObject method
    Customer createdCustomer = restTemplate.postForObject(
        URI_CUSTOMER, newCustomer, Customer.class);
 
    // Returning a Response of 201 CREATED, indicates that a
    // new resource has been created.
    // with the created-customer wrapped into
    // ResponseEntity.
    return new ResponseEntity(createdCustomer,
                              HttpStatus.CREATED);
}
 
@PostMapping("/exchange/customer")
public ResponseEntity
addCustomerUsingExchange(@RequestBody Customer newEmployee)
{
 
    // Instantiate HttpHeaders to add custom properties.
    HttpHeaders httpHeaders = new HttpHeaders();
 
    // set the Accept-header as APPLICATION_JSON to get the
    // content in JSON format
    httpHeaders.setAccept(Collections.singletonList(
        MediaType.APPLICATION_JSON));
 
    // building a HttpEntity using HttpHeaders to
    // customize the request
    HttpEntity<Customer> entity
        = new HttpEntity<>(newEmployee, httpHeaders);
 
    // exchange method can be used for POST request with
    // custom headers, to create a new Customer
      // It also that new created Customer
    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.

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




// for PUT we have two methods in Rest Template
// for changing Customer Resource
 
 
@PutMapping("/put/customer/{id}")
public ResponseEntity<?> updateCustomerUsingPut(
                  @PathVariable Integer id,
                @RequestBody Customer newEmployee){
 
      // creating Map to populate all the parameters
    Map<String, String> params = new HashMap<>();
   
      // adding "id" as parameter
      // similarly you can add Authrization token, if required.
    params.put("id", String.valueOf(id));
   
      // Update call using RestTemplate for Customer Resource
    restTemplate.put(URI_CUSTOMER_ID, newEmployee, params);
   
      // Generating a response of 200 OK
    return new ResponseEntity(
        "Customer Updated with id " + id, HttpStatus.OK);
}
 
@PutMapping("/exchange/customer/{id}")
public ResponseEntity<?> updateCustomerUsingExchange(
                @PathVariable Integer id,
                @RequestBody Customer newEmployee){
   
   
    // set the Accept-header as APPLICATION_JSON to get the
    // content in JSON format
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAccept(Collections.singletonList(
        MediaType.APPLICATION_JSON));
   
      // building a HttpEntity using HttpHeaders and updated
      // customer object to customize the request
    HttpEntity<Customer> entity
        = new HttpEntity<>(newEmployee, httpHeaders);
   
      // sending put request using RestTemplate
    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.

  1. delete: a simple way to send an HTTP DELETE request. It accepts a URL and URI variable (Optional) for requests. No customization is required.
  2. exchange: while handling authentication or working with APIs that require custom headers exchange is the best choice.

Java




// We have 2 methods available for a POST using
// RestTemplate in Spring Boot Application
  
 
@DeleteMapping("/delete/customer/{id}")
public ResponseEntity deleteCustomerUsingDelete(
                          @PathVariable Integer id){
   
   
      // creating Map to populate all the parameters
      // for delete request
    Map<String, String> params = new HashMap<>();
   
    // adding "id" as parameter
      // similarly you can add Authrization token, if required.
    params.put("id", String.valueOf(id));
   
   
      // delete call using RestTemplate for
      // removing Customer Resource
    restTemplate.delete(URI_CUSTOMER_ID, params);
   
   
      // Generating a response of 200 OK
    return new ResponseEntity<>(
        "Customer deleted with id " + id, HttpStatus.OK);
}
 
@DeleteMapping("/exchange/customer/{id}")
public ResponseEntity<Customer> deleteCustomerUsingExchange(
                          @PathVariable Integer id){
   
     // Instantiate HttpHeaders to add custom properties.
    HttpHeaders httpHeaders = new HttpHeaders();
   
    // set the Accept-header as APPLICATION_JSON to get the
    // content in JSON format
    httpHeaders.setAccept(Collections.singletonList(
        MediaType.APPLICATION_JSON));
   
   
    // building a HttpEntity using HttpHeaders to
    // customize the request
    HttpEntity<Customer> entity
        = new HttpEntity<>(httpHeaders);
   
      // sending put request using exchange method
    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) {
        // Handle the exception, e.g., logging or custom
        // error handling.
    }
    return null;
}


Custom Error Handling

Declare your own custom error response form to handle Custom Error Handling.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads