Fast API 활용하기

pitseleh·2025년 5월 27일
post-thumbnail

Python으로 만든 이상거래 탐지와 관련된 API를 Spring에서 호출해야 하는 상황이 발생했다. 선택지로는 Flask와 Fast API가 있었는데, Fast API가 성능이 더 좋고 Swagger를 통한 API 문서도 자동으로 만들어준다고 해서 Fast API로 구현하기로 했다.

계좌 이체 시 이상거래를 탐지하는 플로우는 아래와 같다.

사용자 이체 요청
    ↓
Spring Boot (Bank Service)
    ↓ HTTP POST
FastAPI (Anomaly Service)
    ↓ ML 모델 예측
Isolation Forest 모델
    ↓ 결과 반환
Spring Boot ← 이상거래 여부
    ↓
정상: 이체 진행 / 이상: 계좌 차단

구현은 생각보다 간단했다. 일단 Python쪽 코드에 Fast API를 적용한다.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI()

# 요청 데이터 모델 정의
class TransactionRequest(BaseModel):
    amount: float = Field(..., alias="amount")
    hour_of_day: int = Field(..., alias="hourOfDay")
    is_new_receiver: int = Field(..., alias="isNewReceiver")
    days_since_last_tx: int = Field(..., alias="daysSinceLastTx")

# 예측 엔드포인트
@app.post("/api/anomaly/predict")
async def predict(request: TransactionRequest):
    try:
        # ML 모델 예측 로직
        prediction = model.predict(preprocessed_data)
        is_anomaly = 1 if prediction[0] == -1 else 0
        
        return {"is_anomaly": is_anomaly}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"예측 중 오류 발생: {str(e)}")

위와 같이 작성한 Fast API를 Spring에서 불러오면 된다.

@Service
@RequiredArgsConstructor
public class AnomalyService {
    
    private final RestTemplate restTemplate;
    
    @Value("${api.anomaly-url}")
    private String fastApiUrl; 

    public boolean detectAnomaly(TransactionDto request) {
        try {
            // FastAPI 호출
            PredictionDto response = restTemplate.postForObject(
                fastApiUrl, request, PredictionDto.class);
            
            log.info("이상거래 FAST API 호출 완료");
            return response != null && response.getIsAnomaly() == 1;
        } catch (Exception e) {
            log.error("이상 거래 탐지 중 오류 발생: {}", e.getMessage());
            return false; 
        }
    }
}

0개의 댓글