9/26

졸용·2025년 9월 26일

TIL

목록 보기
84/144

🔹 Rest Template이란?

Spring Framework에서 제공하는 동기식 HTTP 클라이언트를 말한다.

쉽게 말해, 자바 코드 안에서 다른 서버(API)에 HTTP 요청을 보내고 응답을 받아올 수 있도록 도와주는 클래스를 말한다.


🔸특징

  • 동기식(synchronous): 요청을 보내면 응답을 받을 때까지 현재 스레드가 블로킹됨.
  • 간단한 사용법: GET, POST, PUT, DELETE 같은 REST API 호출을 메서드 한두 줄로 처리 가능.
  • 자동 변환: 응답을 원하는 타입(예: String, Map, DTO)으로 변환해 줌.
  • 내부적으로 HttpMessageConverter 사용: JSON → 객체, 객체 → JSON 변환을 자동으로 처리.

🔸자주 쓰는 메서드

RestTemplate restTemplate = new RestTemplate();

// GET 요청
String response = restTemplate.getForObject("https://api.example.com/data", String.class);

// POST 요청
MyRequest req = new MyRequest("value");
MyResponse res = restTemplate.postForObject("https://api.example.com/create", req, MyResponse.class);

// PUT 요청
restTemplate.put("https://api.example.com/update/1", req);

// DELETE 요청
restTemplate.delete("https://api.example.com/delete/1");

➡️ RestTemplate은 Spring에서 제공하는 간단하고 직관적인 REST API 호출 도구지만,
신규 프로젝트에서는 WebClient 사용을 권장한다.

profile
꾸준한 공부만이 답이다

0개의 댓글