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**

Top comments (0)