Spring Boot - Rest Template
Last Updated :
20 Mar, 2025
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.
- 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
// 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.
- 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
// We have 2 methods available for a POST using
// RestTemplate in Spring Boot Application
@PostMapping("/postForObject/customer")
public ResponseEntity<?> addCustomerUsingPostForObject(@RequestBody Customer newCustomer) {
// 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 returns 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.
- 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
// 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.
- 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
// 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.
Similar Reads
Spring Boot - Getting Started
Spring Boot is a part of the larger Spring Framework ecosystem which is known for its comprehensive programming and configuration model for the modern Java-based enterprise applications. Spring Boot has emerged as a go-to framework for creating REST APIs, microservices, and web applications with les
5 min read
Spring Boot - Code Structure
There is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules.
3 min read
How to Configure Spring Boot TestRestTemplate?
The Spring Framework is an open-source framework for creating applications, providing many annotations and features to make development easier. Spring Boot simplifies the setup and development of the Spring applications. One useful utility for testing RESTful web services in Spring Boot is TestRestT
4 min read
Spring Boot - REST Example
In modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
What is Spring Data REST?
Spring Data REST is a framework that exposes Spring Data repositories as RESTful endpoints. It allows you to create REST APIs for your data without having to write any controller code. Under the hood, Spring Data REST uses Spring Data repositories to access and manage data. So you first need to defi
7 min read
Spring - REST XML Response
REST APIs have become increasingly popular due to their simplicity and flexibility in architecting applications. A REST API, which stands for Representational State Transfer, is often referred to as RESTful web services. Unlike traditional MVC controllers that return views, REST controllers return d
8 min read
Spring Boot - Starter Test
Spring Boot is built on top of the spring and contains all the features of spring. It is becoming a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration and setup.
5 min read
Spring Boot Ecosystem
The Spring Framework is one of the most popular frameworks for developing stand-alone Java applications. Spring Boot is a part of the Spring Framework. Spring boot supports rapid application development by automating various manual configurations needed for traditional Spring MVC architecture. Sprin
4 min read
Spring Boot - @Requestmapping
Spring Boot is the most popular framework of Java for building enterprise-level web applications and back-ends. Spring Boot has a handful of features that support quicker and more efficient web app development. Some of them are Auto-configuration, Embedded Server, opinionated defaults, and Annotatio
6 min read
Introduction to Spring Boot
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read