신비한 개발사전

RestTemplate vs RestClient 본문

Backend

RestTemplate vs RestClient

jbilee 2025. 5. 21. 01:05

RestTemplate와 RestClient는 HTTP 요청을 보낼 수 있는 HttpClient다. HttpClient를 활용하면 서버 입장에서도 다른 서버에 HTTP 요청을 전송할 수 있다.

RestTemplate and RestClient share the same infrastructure (i.e. request factories, request interceptors and initializers, message converters, etc.), so any improvements made therein are shared as well. However, RestClient is the focus for new higher-level features.

 

과거 해프닝으로 인해 RestTemplate가 deprecated됐다는 얘기가 돌았지만, RestTemplate도 계속해서 지원되고 있다. 다만 RestClient가 최신 API 스펙에 맞는 더 많은 기능을 수행할 수 있고, Spring도 RestClient 사용을 권장하고 있다. RestClient는 Spring 6.1에 추가되었다.

 

RestTemplate

RestTemplate은 getForEntity, getForObject 등의 메서드를 사용해 호출한 API의 응답 본문을 자바 객체로 매핑해 받아올 수 있는 인터페이스를 제공한다.

public List<Todo> getTodos() {
    try {
        ResponseEntity<Todo[]> response = restTemplate.getForEntity("http://jsonplaceholder.typicode.com/todos/", Todo[].class);
        if (response.getBody() == null) return List.of();
        return Arrays.asList(response.getBody());
    } catch (HttpClientErrorException e) {
        // ...
    }
    return List.of();
}

 

RestClient

RestClient는 내부적으로 RestTemplate을 활용하는, 더욱 사용자 친화적인 API다. RestTemplate에 비해 더욱 직관적인 메서드 네이밍과 메서드 체이닝을 사용하는 것이 특징이다.

public List<Todo> getTodos() {
    Todo[] todoBody = restClient.get()
                .uri("/todos")
                .retrieve()
                .body(Todo[].class);

    return Arrays.asList(todoBody);
}

 

 

개인적으로는 메서드 체이닝을 통해 선언형으로 코드를 작성할 수 있는 RestClient를 더 선호한다. 가독성 측면에서 RestClient의 방식이 코드를 더 빠르게 파악할 수 있는 편이라고 생각한다.

 

또한 RestClient가 더 최신 스펙과 개발 트렌드를 변영한 거라, 기술의 발전이 나날이 빨라지는 시대임을 고려했을 때 장기적으로는 RestClient 사용이 유지보수에 더 수월할 것이라고 판단된다.