Spring Boot에서 API 호출하기

반응형

 

📌 Spring Boot에서 API 호출하기

Spring Boot에서는 외부 API를 호출할 때 RestTemplate(동기)와 WebClient(비동기, 최신 권장) 방식을 주로 사용합니다.


1. RestTemplate (동기 방식)

① Bean 등록

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();
    }
}

② 서비스 코드

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String callApi() {
        String url = "https://api.example.com/data?param=value";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer YOUR_TOKEN"); // 인증 필요시

        HttpEntity entity = new HttpEntity<>(headers);

        ResponseEntity response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );

        return response.getBody();
    }
}

2. WebClient (비동기 / 최신 권장)

① Bean 등록

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient(WebClient.Builder builder) {
        return builder.baseUrl("https://api.example.com").build();
    }
}

② 서비스 코드

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String callApi(String value) {
        return webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/data")
                        .queryParam("param", value)
                        .build()
                )
                .header("Authorization", "Bearer YOUR_TOKEN") // 인증 필요시
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 동기 처리 (비동기로 쓰려면 subscribe())
    }
}

3. 어떤 걸 선택할까?

방식 특징 추천 상황

RestTemplate 간단, 동기 방식, 직관적 빠른 개발, 기존 레거시 코드 유지
WebClient 비동기/리액티브, 고성능 대규모 트래픽, 실시간 데이터 처리

💡 Tip

  • API 호출 시 타임아웃, 예외 처리, 인증 처리는 반드시 포함
  • 응답이 JSON이면 **DTO 매핑(Jackson)**을 사용하면 더 안전하고 깔끔하게 데이터 처리 가능

원하시면 제가 이 내용에 DTO 매핑 예제까지 추가해서 완성형 블로그 글로 만들어드릴까요?
그렇게 하면 실무 예제로 훨씬 강력해집니다.

반응형

Designed by JB FACTORY