RestTemplate사용하여 외부 API 서버 연결방법

박성현·2025년 7월 25일

개발중 학습

목록 보기
10/44

📡 Spring RestTemplate으로 외부 API 호출하기

RestTemplate은 Spring Framework에서 제공하는 HTTP 통신 클라이언트입니다.
외부 REST API와 통신할 때 간단하게 사용할 수 있으며, JSON 데이터 전송/수신에 특히 유용합니다.


✅ RestTemplate 기본 개념

  • Spring에서 제공하는 HTTP 요청 도구
  • RESTful API 호출을 매우 쉽게 구현 가능
  • 주로 GET, POST, PUT, DELETE 요청에 사용됨
  • 응답 결과를 String, Map, 또는 DTO 객체로 쉽게 매핑 가능

✅ 1. GET 요청 보내기

import org.springframework.web.client.RestTemplate;

public class RestTemplateGetExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        String url = /* 요청하고자 하는 url 주소 */;
        String response = restTemplate.getForObject(url, String.class);

        System.out.println("GET 응답 결과:");
        System.out.println(response);
    }
}

✅ 2. POST 요청 보내기 예시 CODE (JSON 데이터 전송)

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class RestTemplatePostExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
	
        String url = /* 요청하고자 하는 url 주소 */;

        // JSON 전송을 위한 데이터 구성
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("title", "foo");
        requestBody.put("body", "bar");
        requestBody.put("userId", 1);

        // 헤더 설정
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // HttpEntity에 헤더와 바디 담기
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // POST 요청 보내기
        String response = restTemplate.postForObject(url, entity, String.class);

        System.out.println("POST 응답 결과:");
        System.out.println(response);
    }
}

✅ RestTemplate vs WebClient

항목RestTemplateWebClient
방식동기 (Blocking)비동기 (Non-blocking, Reactive)
사용성간단하고 익숙함복잡하지만 유연함
권장 여부Spring 5 이하에서 유용Spring 5 이상에서 권장됨

✅ 결론

  • RestTemplate은 간단한 HTTP 요청에 적합하며, 동기 방식으로 작동합니다.
  • Spring 5 이후에는 WebClient 사용이 권장되지만, 레거시 시스템이나 단순 호출에는 여전히 유용합니다.
  • 외부 API를 호출할 때, 사용 목적에 따라 적절한 HTTP 클라이언트를 선택하세요.
profile
개발기록장

0개의 댓글