Due to high traffic and quick access to services, REST APIs are getting more popular. REST is not a protocol or a way of standard, rather it is a set of architectural constraints. It is also called 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:
- JSON (JavaScript Object Notation )
- XML
- HTML
- XLT
- Python
- PHP
- Plain text
Pre-requisites: The ‘Client’ can be of any front-end framework like Angular, React for reasons like developing 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’s 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’.
Consuming REST API is as Follows:

‘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.
|
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:
- One accepts a String URL specification with URL parameters specified in a variable argument list.
- One accepts a String URL specification with URL parameters specified in a Map<String, String>.
- One accepts a java.net.URI as the URL specification, with no support for parameterized URLs.
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:
// Annotation
@Bean
// Method
public RestTemplate restTemplate()
{
return new RestTemplate();
}

Project Structure – Maven
File: pom.xml (Configurations)
XML
<?xml version="1.0" encoding="UTF-8"?>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/>
</parent>
<groupId>sia</groupId>
<artifactId>GFG-RestTemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GFG-RestTemplate</name>
<description>Rest-Template</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
File: GfgRestTemplateApplication.java (Bootstrapping of application)
Java
package gfg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GfgRestTemplateApplication {
public static void main(String[] args)
{
SpringApplication.run(
GfgRestTemplateApplication.class, args);
}
}
|
A. File: UserData.java (Domain class)
- 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 – pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Example:
Java
package gfg;
import lombok.Data;
@Data
public class UserData {
public String id;
public String userName;
public String data;
}
|
B. RestApiController.java (Rest Controller – REST API)
- GET – Returns domain data in JSON form.
- POST- Returns domain data wrapped in ResponseEntity along with headers.
Example:
Java
package gfg;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/RestApi",
produces = "application/json")
@CrossOrigin(origins = "*")
public class RestApiController {
@GetMapping("/getData") public UserData get()
{
UserData userData = new UserData();
userData.setId("1");
userData.setUserName("darshanGPawar@geek");
userData.setData("Data send by Rest-API");
return userData;
}
@PostMapping
public ResponseEntity<UserData>
post(@RequestBody UserData userData)
{
HttpHeaders headers = new HttpHeaders();
return new ResponseEntity<>(userData, headers,
HttpStatus.CREATED);
}
}
|
C. File: RestTemplateProvider.java (RestTemplate implementation)
- GET – Consumes REST API’s GET mapping response and returns domain object.
- POST – Consumes REST API’s POST mapping response and return ResponseEntity object.
Example:
Java
package gfg;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestTemplateProvider {
RestTemplate rest = new RestTemplate();
public UserData getUserData()
{
return rest.getForObject(
UserData.class);
}
public ResponseEntity<UserData> post(UserData user)
{
return rest.postForEntity(
UserData.class, "");
}
}
|
D. File: ConsumeApiController.java (Regular Controller – Consume REST API)
Uses RestTemplate to get the data from REST API and accordingly changes and returns a view.
Java
package gfg;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/Api")
public class ConsumeApiController {
@GetMapping public String get(Model model)
{
RestTemplateProvider restTemplate
= new RestTemplateProvider();
model.addAttribute("user",
restTemplate.getUserData());
model.addAttribute("model", new UserData());
return "GetData";
}
@PostMapping
public String post(@ModelAttribute("model")
UserData user, Model model)
{
RestTemplateProvider restTemplate = new RestTemplateProvider();
ResponseEntity<UserData> response = restTemplate.post(user);
model.addAttribute("user", response.getBody());
model.addAttribute("headers",
response.getHeaders() + " "
+ response.getStatusCode());
return "GetData";
}
}
|
E. File: GetData.html ( Display the results – Thymeleaf Template)
HTML
<!DOCTYPE html>
<head>
<title>GFG-REST-TEMPLATE</title>
<style>
h1{
color:forestgreen;
}
p{
width:500px;
}
</style>
</head>
<body>
<h1>Hello Geek</h1>
<h1 th:text="${user.id}"> Replaceable text </h1 >
<h1 th:text="${user.userName}"> Replaceable text </h1 >
<h1 th:text="${user.data}"> Replaceable text </h1 >
<form method="POST" th:object="${model}">
<label for="id">Type ID : </label><br/>
<input type="text" th:field="*{id}"><br/>
<label for="userName">Type USERNAME : </label><br/>
<input type="text" th:field="*{userName}"><br/>
<label for="data">Type DATA : </label><br/>
<input type="text" th:field="*{data}">
<input type="submit" value="submit">
</form>
<p th:text="${headers}"></p>
</body>
</html>
|
Outputs: They are as follows sequentially

( GET request )

( POST request )
Note:
- When your Back-end Spring application acts as a Client of REST API of the same or another Spring application, RestTemplate makes it convenient and avoids tedium effort.
- When you are dealing with an HTTPS URL, you will get errors if you are using a self-signed certificate. It is better to work with HTTP for development purposes.
Similar Reads
Spring Boot - Architecture
The Spring Boot is built on top of the core Spring framework. It is a simplified and automated version of the spring framework. The spring boot follows a layered architecture in which each layer communicates to other layers(Above or below in hierarchical order). The spring boot documentation provide
2 min read
Spring Boot Actuator
Developing and Managing an application are the two most important aspects of the application's life cycle. It is very crucial to know what's going on beneath the application. Also when we push the application into production, managing it gradually becomes critically important. Therefore, it is alway
5 min read
Spring Boot - Introduction to RESTful Web Services
RESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of HTTP protocol. It uses the concepts and verbs alr
5 min read
How to create a basic application in Java Spring Boot
Spring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
3 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. In this article, we will go through a step-by-step guide on how to create a RESTful API in Spring Boot with MySQL and JPA. We will start by creating a new Spring Boot project and configuring it for our needs. Step-by-Step
11 min read
Java Spring Boot Microservices Sample Project
Microservices are more popular nowadays. They can be written in any language. In this article, let us see Spring Boot Microservices. in this article let us see a base project "currency-exchange-sample-service" which has a business logic and which can be invoked in another project "currency-conversio
9 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Con
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C+
4 min read
Best Practices For Structuring Spring Boot Application
Spring Boot is built on top of the conventional spring framework. So, it provides all the features of spring and is yet easier to use than spring. In this article, we are going to see how one should start and structure his Spring Boot application. Prerequisites: Good knowledge of Java.Basic knowledg
3 min read