Below is a mini-guide (with runnable snippets) that shows one clean way to expose your own REST endpoint in Spring Boot that, when invoked, calls a remote REST service and returns (or transforms) the result.
You can do it with either
the older RestTemplate (still OK for simple, blocking calls) or
the modern, non-blocking WebClient (preferred for new code).
I’ll show both; pick the style your project/team is using.
0. Project Setup
Maven pom.xml (Gradle equivalent works the same):
xml
<dependencies>
<!-- Your own REST controller -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- If you plan to use WebClient (reactive) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- Optionally: Lombok to cut boilerplate -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
1. Directory Layout
code
src/main/java
└─ com.example.demo
├─ DemoApplication.java // main()
├─ controller
│ └─ ProxyController.java // REST entry point
└─ service
└─ RemoteApiService.java // calls the remote API
2. The POJO (whatever the remote API returns)
Let’s say the remote API returns JSON like:
json
{
"id": 123,
"title": "foo",
"completed": false
}
Define:
java
@Data // Lombok (or write getters/setters manually)
public class TodoDto {
private Long id;
private String title;
private Boolean completed;
}
3A. Implementation using RestTemplate (blocking)
RemoteApiService.java
java
@Service
public class RemoteApiService {
private final RestTemplate restTemplate;
public RemoteApiService(RestTemplateBuilder builder) {
this.restTemplate = builder
.rootUri("https://jsonplaceholder.typicode.com") // example base URL
.setConnectTimeout(Duration.ofSeconds(2))
.setReadTimeout(Duration.ofSeconds(2))
.build();
}
public TodoDto fetchTodo(Long id) {
String path = "/todos/{id}";
try {
return restTemplate.getForObject(path, TodoDto.class, id);
} catch (RestClientException ex) {
throw new RemoteCallFailedException("Cannot reach remote service", ex);
}
}
}
ProxyController.java
java
@RestController
@RequestMapping("/api")
public class ProxyController {
private final RemoteApiService service;
public ProxyController(RemoteApiService service) {
this.service = service;
}
@GetMapping("/todo/{id}")
public ResponseEntity<TodoDto> getTodo(@PathVariable Long id) {
TodoDto dto = service.fetchTodo(id);
return ResponseEntity.ok(dto);
}
}
Bean config (optional, if you want one shared RestTemplate):
java
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
3B. Implementation using WebClient (non-blocking)
RemoteApiService.java
java
@Service
public class RemoteApiService {
private final WebClient client;
public RemoteApiService(WebClient.Builder builder) {
this.client = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
public Mono<TodoDto> fetchTodo(Long id) {
return client.get()
.uri("/todos/{id}", id)
.retrieve() // do HTTP exchange
.bodyToMono(TodoDto.class) // map JSON -> POJO
.timeout(Duration.ofSeconds(2)) // optional
.onErrorMap(ex -> new RemoteCallFailedException("Remote API blew up", ex));
}
}
ProxyController.java
java
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class ProxyController {
private final RemoteApiService service;
@GetMapping("/todo/{id}")
public Mono<ResponseEntity<TodoDto>> getTodo(@PathVariable Long id) {
return service.fetchTodo(id)
.map(ResponseEntity::ok);
}
}
Spring Boot auto-configures a global WebClient.Builder; no extra bean needed unless you want custom timeouts, codecs, etc.
4. Exception Handling
Create your own exception:
java
public class RemoteCallFailedException extends RuntimeException {
public RemoteCallFailedException(String msg, Throwable cause) {
super(msg, cause);
}
}
And a controller advice:
java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RemoteCallFailedException.class)
public ResponseEntity<Map<String, String>> handleRemote(RemoteCallFailedException ex) {
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", ex.getMessage()));
}
}
5. Testing it
Run the Spring Boot app (DemoApplication.java).
Call your API:
code
curl http://localhost:8080/api/todo/1
Response is the JSON fetched from https://jsonplaceholder.typicode.com/todos/1.
6. Tips & Best Practices
• Prefer WebClient for new, reactive or concurrent code.
• Wrap the remote call in a service layer, not directly in the controller.
• Use @ConfigurationProperties to externalize the remote base URL and timeouts.
• Consider resilience patterns: retry, circuit breaker (resilience4j, Spring Cloud CircuitBreaker) for production.
• Log at DEBUG the request/response (ExchangeFilterFunction in WebClient or ClientHttpRequestInterceptor in RestTemplate) only if you mask sensitive data.
• Use DTOs to shield your API from changes in the remote API.
Now you have a tidy Spring REST endpoint that proxies (or aggregates) a remote REST call. Happy coding! 🚀