✅ What is RestTemplate?
RestTemplate is a synchronous client to perform HTTP requests in a Spring application (mostly used before WebClient).
🔧 Example: Using RestTemplate to Call an External API
💡 Scenario: Call a public API that returns user data (like https://jsonplaceholder.typicode.com/users/1)
Create the Spring Boot project Using Spring web Dependency
Directory Structure :
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.4.5
com.example
RestTemplateExample
0.0.1-SNAPSHOT
RestTemplateExample
Demo project for Spring Boot
17
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
🔹 Step 1: Add RestTemplate Bean in Configuration
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
🔹 Step 2: Create a DTO for the Response (Optional but good practice)
package com.example.demo.model;
public class User {
private int id;
private String name;
private String username;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", username=" + username + ", email=" + email + "]";
}
}
🔹 Step 3: Use RestTemplate in a Service or Controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.example.demo.model.User;
@RestController
public class ExternalApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/user")
public User getUser() {
String url = "https://jsonplaceholder.typicode.com/users/1";
return restTemplate.getForObject(url, User.class);
}
}
✅ Output (JSON response):
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]"
}