본문 바로가기

Study Information Technology

Spring Boot와 외부 API 통합하기

728x90
반응형

Spring Boot와 외부 API 통합하기

Overview

Spring Boot는 자바 기반의 프레임워크로, 웹 애플리케이션 개발을 간소화하는 데 큰 도움을 줍니다. 특히 외부 API와의 통합을 통해 다양한 서드파티 서비스와 데이터를 활용할 수 있습니다. 이번 글에서는 Spring Boot에서 외부 API를 통합하는 방법을 구체적으로 설명하고, 예제 코드와 함께 발생할 수 있는 오류 및 해결책을 소개하겠습니다.


1. Spring Boot란?

Spring Boot는 Spring Framework를 기반으로 하여, 개발자가 복잡한 설정 없이도 손쉽게 애플리케이션을 구축할 수 있도록 해주는 도구입니다.

특징

  • 자동 구성(Auto-configuration): 개발자가 직접 설정하지 않아도 Spring이 알아서 필요한 빈(bean)을 생성해줍니다.
  • 의존성 관리(Dependency Management): Maven 또는 Gradle을 통해 필요한 라이브러리를 쉽게 관리할 수 있습니다.
  • Standalone: 독립적으로 실행할 수 있는 JAR 파일을 생성할 수 있습니다.

2. 외부 API 통합의 필요성

외부 API와의 통합은 여러모로 유용합니다.

예시

  • 데이터 수집: 날씨 API를 사용하여 실시간 날씨 정보를 제공하는 애플리케이션.
  • 결제 시스템: Stripe API를 통해 결제 기능을 추가.
  • 소셜 미디어 연동: Twitter API를 사용하여 사용자의 트윗을 불러오는 기능.

3. 외부 API 호출하기

외부 API를 호출하기 위해선 HTTP 클라이언트 라이브러리를 사용할 수 있습니다. Spring Boot에서는 RestTemplateWebClient를 자주 사용합니다.

RestTemplate 사용 예제

RestTemplate은 동기적인 HTTP 요청을 보내는 데 사용됩니다.

의존성 추가

먼저, pom.xml 파일에 Spring Web 의존성을 추가합니다.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

코드 작성

이제 RestTemplate을 사용하여 외부 API를 호출하는 방법을 살펴보겠습니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

private final RestTemplate restTemplate;

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

public String fetchDataFromApi(String url) {
try {
String response = restTemplate.getForObject(url, String.class);
return response;
} catch (Exception e) {
System.out.println("API 호출 중 오류 발생: " + e.getMessage());
return null;
}
}
}

위의 코드는 주어진 URL에서 데이터를 가져오는 간단한 서비스 클래스입니다. getForObject 메소드를 사용하여 GET 요청을 보내고, 응답을 문자열 형태로 반환합니다.

4. API 응답 처리

API 호출 후 응답 데이터를 처리하는 방법도 중요합니다. API는 일반적으로 JSON 형식의 데이터를 반환합니다. 이를 위해 DTO(Data Transfer Object)를 만들어 데이터를 매핑할 수 있습니다.

DTO 클래스 예시

import com.fasterxml.jackson.annotation.JsonProperty;

public class WeatherResponse {

@JsonProperty("main")
private Main main;

// Getter and Setter
}

class Main {
private double temp;

// Getter and Setter
}

JSON 데이터 매핑

이제 API 호출 시 JSON 응답을 WeatherResponse 객체로 매핑하는 방법을 알아보겠습니다.

public WeatherResponse fetchWeather(String url) {
try {
WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class);
return response;
} catch (Exception e) {
System.out.println("API 호출 중 오류 발생: " + e.getMessage());
return null;
}
}

5. 에러 처리

외부 API와 통신할 때는 다양한 오류가 발생할 수 있습니다. 이러한 오류를 효과적으로 처리하는 것이 중요합니다.

일반적인 오류 유형

  • 404 Not Found: 요청한 URL이 잘못되었거나, 서버에 해당 리소스가 없습니다.
  • 500 Internal Server Error: 서버에서 예기치 않은 오류가 발생했습니다.
  • Connection Timeout: API 서버에 연결할 수 없는 경우.

예외 처리 방법

Spring에서는 @ControllerAdvice를 사용하여 전역적으로 예외를 처리할 수 있습니다.

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAllExceptions(Exception ex) {
return "오류 발생: " + ex.getMessage();
}
}

6. 테스트 및 검증

API 통합 후에는 이를 테스트하는 것도 중요합니다. JUnit과 MockMvc를 사용하여 통합 테스트를 수행할 수 있습니다.

테스트 코드 예시

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApiServiceTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private ApiService apiService;

@Test
public void testFetchDataFromApi() throws Exception {
when(apiService.fetchDataFromApi("http://example.com/api")).thenReturn("mock response");

mockMvc.perform(get("/api"))
.andExpect(status().isOk());
}
}

이 테스트는 ApiService가 주어진 URL에서 데이터를 성공적으로 가져오는지를 검증합니다.


7. 공식 문서 및 참고 자료

마지막으로, Spring Boot와 외부 API 통합에 대한 자세한 내용은 공식 문서를 참조하실 수 있습니다.

이와 같이 Spring Boot와 외부 API를 통합하는 방법에 대해 알아보았습니다. 이를 통해 다양한 서드파티 서비스와의 연동이 가능해지며, 애플리케이션의 기능을 확장할 수 있습니다.

반응형