DEV Community

Sri
Sri

Posted on

Rest Template - API for developers- Spring Boot

RestTemplate is a synchronous Spring Framework client used to consume RESTful web services by simplifying HTTP communication.
Synchronous Communication: It blocks the execution thread until a response is received.HTTP Methods: It provides built-in methods for standard operations like GET, POST, PUT, and DELETE.Automatic Mapping: It can automatically convert JSON or XML responses into Java domain objects using message converters.Status: While widely used, it is in maintenance mode. For new projects, Spring recommends using the modern RestClient or the reactive.

Its an automate work.

getForObject() Performs a GET request and returns the response body directly as an object.
getForEntity() Performs a GET request and returns a ResponseEntity (includes status and headers).
postForObject() Sends data via POST and returns the mapped response body.
exchange() A general-purpose method for all HTTP verbs, offering full control over headers and request entities.

getForObject-
Controller Snippet
Response is received in Object format.
@RestController
@RequestMapping("/api")
public class ApiController {

@Autowired
private ApiService apiService;

@GetMapping("/getUsers")
public String users() {
    return apiService.getUsers();
}
Enter fullscreen mode Exit fullscreen mode

Service snippet:
@Service
public class ApiService {

@Autowired
private RestTemplate restTemplate;
@Autowired
UserApiRepo userApiRepo;
public String getUsers() {

    String url = "https://jsonplaceholder.typicode.com/users";

    String response = restTemplate.getForObject(url, String.class);

    return response;
}
Enter fullscreen mode Exit fullscreen mode

Response:

"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}
Enter fullscreen mode Exit fullscreen mode

getForEntity()
Response is received in ResponseEntity Format. It has Response Header,Response body an response.
@GetMapping("/callGetEntityApi/{id}")
public String callApi(@PathVariable String id) {

    RestTemplate restTemplate = new RestTemplate();

    String url = "https://jsonplaceholder.typicode.com/posts/"+id;

    ResponseEntity<String> response =
            restTemplate.getForEntity(url, String.class);
   System.out.println("response.getStatusCode() " +response.getStatusCode() +"response.getHeaders() " +response.getHeaders());
    return response.getBody();
}
Enter fullscreen mode Exit fullscreen mode

Output:
http://localhost:8080/api/callGetEntityApi/1
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

LogS:
2026-05-29T18:09:20.680+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] o.s.web.client.RestTemplate : Response 200 OK
2026-05-29T18:09:20.682+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] o.s.web.client.RestTemplate : Reading to [java.lang.String] as "application/json;charset=utf-8"
2026-05-29T18:09:20.688+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3]** m.m.a.RequestResponseBodyMethodProcessor : Using 'text/plain', given [/] and supported [text/plain, /, application/json, application/+json]*
2026-05-29T18:09:20.690+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Writing ["[ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april. (truncated)..."]
2026

** PostForOject-**
Service:
public String createPost(JSOnRequest jsOnRequest) {

    String url = "https://jsonplaceholder.typicode.com/posts";

    Map<String, Object> body = new HashMap<>();

    body.put("title",jsOnRequest.getTitle() );
    body.put("body", jsOnRequest.getBody());
    body.put("userId", jsOnRequest.getUserId());

    String response = restTemplate.postForObject(
            url,
            body,
            String.class
    );

    return response;
}
**Controller**
 @PostMapping("/postUsers")
public String postUsers(JSOnRequest request) {
    return apiService.createPost(request);
}
Enter fullscreen mode Exit fullscreen mode

** Output**

"title": "Java3",
"body": "Dell-Dark",
"userId": "4",
"id": 101

headforheaders
Service
public MediaType getheadforheaders(){
String url = "https://jsonplaceholder.typicode.com/users";
HttpHeaders response = restTemplate.headForHeaders(url);
log.info(response.toString());
@Nullable MediaType responseList = response.getContentType();
return responseList;
}

Controller
@GetMapping("/getheadforheaders")
public MediaType headforheaders() {
return apiService.getheadforheaders();
}
Output
{
"charset": "UTF-8",
"concrete": true,
"parameters": {
"charset": "utf-8"
},
"qualityValue": 1.0,
"subtype": "json",
"subtypeSuffix": null,
"type": "application",
"wildcardSubtype": false,
"wildcardType": false
}
delete
Service
public String getdeleteUser(Integer bookid){
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/book/DeleteBookDetails/{bookId}";
restTemplate.delete(url,bookid);
return "Success";
}
Controller:
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable Integer id) {
return apiService.getdeleteUser(id);
}
http://localhost:8080/api/deleteUser/3
output :: success

PostForEntity
@PostMapping("/send")
public String sendRequest(@RequestBody Laptop laptop) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/Laptop/saveLaptop";
log.info("laptop.getModelName() "+laptop.getModelName()+"laptop.getLaptopModelId() " +laptop.getLaptopModelId()
+"laptop.getPrice() " +laptop.getPrice());
ResponseEntity response =restTemplate.postForEntity(
url,
laptop,
String.class);
log.info(response.getStatusCode().toString());
return response.getBody();
}
RestTemplate.exchange() is the most flexible method in RestTemplate. It allows you to specify:

  1. HTTP method (GET, POST, PUT, DELETE, etc.)
  2. Request headers
  3. Request body
  4. Response type Method Signature: ResponseEntity exchange( String url, HttpMethod method, HttpEntity<?> requestEntity, Class responseType )

Example
@RequestMapping("/getExchange")
public ResponseEntity getExchange(HttpServletRequest request){
RestTemplate restTemplate = new RestTemplate(); // Initiate restTemplate
//Get BearerAuth from Heaer
String token=getBearertokenFromRequest(request);
log.info("token "+token);
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
//Perform Exchange Activity
HttpEntity entity = new HttpEntity<>(headers);
String URL="http://localhost:8080/book/getBookDetailsForID/6";
ResponseEntity response =
restTemplate.exchange(
URL,
HttpMethod.GET,
entity,
String.class
);

System.out.println(response.getBody());
return response;
Enter fullscreen mode Exit fullscreen mode

}
public String getBearertokenFromRequest(HttpServletRequest request){
System.out.println("insie token");
String authHeader=request.getHeader("Authorization");
log.info("authHeader "+authHeader);
if(authHeader.startsWith("Bearer ")) {
return authHeader.substring(7);
}
return "Invalid Token";
}

}

Top comments (0)