반응형
전자정부프레임워크를 활용하여 외부 API와의 연동 방법을 학습합니다. 외부 데이터를 가져오거나 서비스를 제공받기 위해 REST API를 호출하는 방법과 데이터를 처리하는 주요 전략을 다룹니다.
1. 외부 API 연동의 필요성
- 외부 데이터 활용: 예를 들어, 날씨 데이터, 금융 정보, 또는 지도 API 등.
- 외부 서비스 통합: 결제, 로그인(OAuth), 알림 서비스 등 다양한 외부 기능 활용.
2. 외부 API 연동 방식
- REST API 호출
대부분의 외부 서비스는 HTTP 프로토콜을 기반으로 RESTful API를 제공합니다. - HTTP 클라이언트 사용
Spring에서는 외부 API 호출을 위해 RestTemplate 또는 최신 WebClient를 사용합니다.
3. RestTemplate을 이용한 API 호출
3-1. RestTemplate 설정
RestTemplate은 Spring에서 제공하는 동기식 HTTP 클라이언트입니다.
Bean 등록:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3-2. GET 요청 예제
외부 API로부터 데이터를 가져오는 방법:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/api/weather")
public String getWeather() {
String url = "https://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=your_api_key";
return restTemplate.getForObject(url, String.class);
}
}
3-3. POST 요청 예제
외부 API로 데이터를 전송하는 방법:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@PostMapping("/api/send-data")
public String sendData() {
String url = "https://api.example.com/send";
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
String requestBody = "{ \"message\": \"Hello, API!\" }";
HttpEntity requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
}
4. WebClient를 이용한 API 호출 (비동기식)
WebClient는 비동기 HTTP 호출에 적합하며, 더 높은 성능과 유연성을 제공합니다.
4-1. WebClient 설정
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() {
return WebClient.builder().build();
}
}
4-2. GET 요청 예제
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class ApiController {
@Autowired
private WebClient webClient;
@GetMapping("/api/async-weather")
public Mono getAsyncWeather() {
String url = "https://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=your_api_key";
return webClient.get()
.uri(url)
.retrieve()
.bodyToMono(String.class);
}
}
5. JSON 데이터 처리
외부 API에서 가져온 데이터는 대부분 JSON 형식입니다. 이를 처리하려면 ObjectMapper 또는 Jackson 라이브러리를 사용합니다.
예제: JSON 데이터를 객체로 변환
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/api/weather-json")
public String getWeatherAsJson() throws Exception {
String url = "https://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=your_api_key";
String jsonResponse = restTemplate.getForObject(url, String.class);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(jsonResponse);
String weather = root.path("weather").get(0).path("description").asText();
return "현재 날씨: " + weather;
}
}
6. API 연동 시 주의할 점
- API 키 보안
- API 키를 코드에 하드코딩하지 말고 환경 변수 또는 설정 파일에 저장하세요.
- 타임아웃 설정
- RestTemplate 또는 WebClient에 타임아웃을 설정하여 무한 대기를 방지하세요.
- 에러 처리
- HTTP 상태 코드에 따라 적절한 에러 처리가 필요합니다.
- 요청 빈도 제한 확인
- 외부 API는 대부분 요청 빈도 제한이 있으므로 이를 초과하지 않도록 주의합니다.
7. 마무리
오늘 학습에서는 전자정부프레임워크 기반의 REST API 프로젝트에서 외부 API 연동 방법을 배웠습니다. RESTful 방식의 요청과 JSON 데이터 처리 기술은 현대 웹 개발에서 필수적이며, 앞으로 다양한 외부 서비스와의 연동에서 유용하게 사용될 것입니다.
다음에서는 Spring Boot와 파일 업로드/다운로드 처리를 다룹니다.
반응형
'개발 > 전자정부프레임워크' 카테고리의 다른 글
전자정부프레임워크 기반 로그인 인증 처리 (0) | 2024.12.27 |
---|---|
파일 업로드 및 다운로드 구현 (0) | 2024.12.27 |
REST API와 CORS 설정 이해 및 구현 (0) | 2024.12.27 |
전자정부프레임워크에서 REST API 보안 강화 (1) | 2024.12.26 |
전자정부프레임워크에서 역할 기반 권한 관리(Role-Based Access Control) 구현 (0) | 2024.12.26 |