![]() |
VOOZH | about |
Due to high traffic and quick access to services, REST APIs are getting more popular and have become the backbone of modern web development. It provides quick access to services and also provides fast data exchange between applications. REST is not a protocol or a standard, rather, it is a set of architectural constraints. It is also called a RESTful API or web API. When a client request is made, it just transfers a representation of the state of the resource to the requester or at the endpoint via HTTP. This information delivered to the client can be in several formats as follows:
Key Features of RestTemplate:
The key features of RestTemplate are listed below:
RestTemplate is a tool that makes it easier to talk to other web services from the Spring application. RestTemplate is useful in various ways which are listed below:
Note: RestTemplate is deprecated as of Spring 5. It is recommended to use WebClient from Spring WebFlux, it supports non-blockin and reactive communication.
Pre-requisites: The Client can be of any front-end framework like Angular, React, for reasons like developing a Single Page Application (SPA ), etc. or it can be a back-end internal/external Spring application itself.
To interact with REST, the client needs to create a client instance and request object, execute the request, interpret the response, map the response to domain objects, and also handle the exceptions. It is common for the Spring framework to both create an API and consume internal or external application APIs. This advantage also helps us in the development of microservices. To avoid such boilerplate code, Spring provides a convenient way to consume REST APIs through RestTemplate.
The image below demonstrates the flow of requesting and getting a resource using Spring Framework, with RestTemplate for requesting and RestAPI for retrieving the resource.
RestTemplate is a synchronous REST client provided by the core Spring Framework.
Path:
org.springframework.web.client.RestTemplate
Constructors:
RestTemplate()
RestTemplate(ClientHttpRequestFactory requestFactory)
RestTemplate(List<HttpMessageConverter<?>> messageConverters)
It provides a total of 41 methods for interacting with REST resources. But there are only a dozen of unique methods each overloaded to form a complete set of 41 methods.
The below table demonstrates the main HTTP operations using RestTemplate
Operation | Method | Action Performed |
|---|---|---|
DELETE | delete() | Performs an HTTP DELETE request on a resource at a specified URL. |
GET | getForEntity() getForObject() | Sends an HTTP GET request, returning a ResponseEntity containing an object mapped from the response body. Sends an HTTP GET request, returning an object mapped from a response body. |
POST | postForEntity() postForLocation() postForObject() | POSTs data to a URL, returning a ResponseEntity containing an object mapped from the response body. POSTs data to a URL, returning the URL of the newly created resource. POSTs data to a URL, returning an object mapped from the response body. |
PUT | put() | PUTs resource data to the specified URL. |
PATCH | patchForObject() | Sends an HTTP PATCH request, returning the resulting object mapped from the response body. |
HEAD | headForHeaders() | Sends an HTTP HEAD request, returning the HTTP headers for the specified resource URL. |
ANY | exchange() execute() | Executes a specified HTTP method against a URL, returning a ResponseEntity containing an object. Executes a specified HTTP method against a URL, returning an object mapped from the response body. |
OPTIONS | optionsForAllow() | Sends an HTTP OPTIONS request, returning the Allow header for the specified URL. |
Except for TRACE, RestTemplate has at least one method for each of the standard HTTP methods. execute() and exchange() provide lower-level, general-purpose methods for sending requests with any HTTP method. Most of the above methods overload in these 3 forms:
In order to use RestTemplate, we can create an instance via as shown below:
RestTemplate rest = new RestTemplate();
Also, you can declare it as a bean and inject it as shown below as follows:
The Project structure is as follow:
To use RestTemplate, include the necessary dependencies in the pom.xml file:
pom.xml( Maven Configurations):
Create a Spring Boot application class to bootstrap the application.
GfgRestTemplateApplication.java (Bootstrapping of application):
This class uses the Lombok library to automatically generate Getter/Setter methods with @Data annotation. Lombok's dependency is as depicted below as follows:
Maven Dependency:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
UserData.java (Domain class):
Create a REST controller to expose endpoints for GET and POST requests.
RestApiController.java (Rest Controller):
Create a class to implement RestTemplate for consuming the REST API.
File: RestTemplateProvider.java (RestTemplate implementation):
Create a regular controller to interact with the REST API and display the results.
ConsumeApiController.java (Regular Controller - Consume REST API):
Create a Thymeleaf template (GetData.html) to display the results.
GetData.html:
Outputs: They are as follows sequentially
Note: