Hackforge Academy

Category: spring_boot

RestTemplate in spring boot

Published on 24 Jun 2026

Explanation

RestTemplate is a synchronous HTTP client provided by Spring Framework for consuming external REST APIs. It supports HTTP methods such as GET, POST, PUT, and DELETE.

Code:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Explanation

To consume an external API, inject the RestTemplate bean into a service or controller. The getForObject() method is commonly used to retrieve data from an external endpoint.

Code:

@Autowired
private RestTemplate restTemplate;

String response = restTemplate.getForObject(
    "https://www.apirequest.in/api/user",
    String.class
);

Explanation

A REST API endpoint can call an external service and return its response directly to the client. This pattern is commonly used in microservices.

Code:

@RestController
@RequestMapping("/posts")
public class PostController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/{id}")
    public String getPost(
@PathVariable Long id) {
        return restTemplate.getForObject(
"https://www.apirequest.in/api/user" +
 id,
            String.class
        );
    }
}

Explanation

External API responses can be mapped directly to Java objects instead of using raw JSON strings. This improves type safety and code readability.

Code:

public class Post {
    private Long id;
    private String title;
    private String body;

    // Getters and Setters
}

Post post = restTemplate.getForObject(
    "https://www.apirequest.in/api/user",
    Post.class
);

Explanation

The exchange() method provides full control over HTTP requests, including headers, request bodies, and response handling. It is useful for advanced API integrations.

Code:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");

HttpEntity<String> entity =
 new HttpEntity<>(headers);

ResponseEntity<String> response = 
restTemplate.exchange(
    "https://www.apirequest.in/api/user",
    HttpMethod.GET,
    entity,
    String.class
);

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community