FastAPI — 고성능 Python 웹 프레임워크

Summary

비동기(async) 기반의 현대적 Python 웹 프레임워크. 자동 타입 검증, OpenAPI 문서 자동 생성, 내장 보안 기능.

비동기(async) 기반의 현대적 Python 웹 프레임워크. 자동 타입 검증, OpenAPI 문서 자동 생성, 내장 보안 기능.

개요

FastAPI는 Starlette의 비동기 재단과 Pydantic의 타입 검증을 결합하여 Python API 개발을 단순화한다.

핵심 강점:

  • 성능: 비동기 I/O로 높은 동시성 처리
  • 타입 안전성: Python 3.7+ 타입 힌트로 자동 유효성 검증
  • 문서 자동화: /docs (Swagger UI), /redoc (ReDoc)
  • 보안: OAuth2, API Key, JWT 토큰 내장
  • 개발 생산성: 보일러플레이트 최소화

최소 예제

from fastapi import FastAPI
 
app = FastAPI()
 
@app.get("/")
async def read_root():
    return {"hello": "world"}
 
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

실행:

uvicorn main:app --host 0.0.0.0 --port 8000

문서:

주요 기능

타입 힌트 검증

from pydantic import BaseModel
 
class User(BaseModel):
    name: str
    age: int
 
@app.post("/users/")
async def create_user(user: User):
    return user

FastAPI가 자동으로:

  1. JSON 바디를 User 모델로 파싱
  2. 자료형 검증 (age는 정수)
  3. 문서에 스키마 추가

비동기 처리

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    # I/O 대기(DB 조회, 외부 API) 중 다른 요청 처리
    result = await fetch_from_database(item_id)
    return result

헬스체크 엔드포인트

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

프로덕션 배포 시 Docker/Kubernetes가 이 엔드포인트를 정기적으로 호출하여 컨테이너 자동 재시작 여부 판단.

요청 로깅 미들웨어

from fastapi import Request
import time
 
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start
    print(f"method={request.method} path={request.url.path} status={response.status_code} duration={duration:.3f}s")
    return response

Uvicorn과의 관계

Uvicorn: FastAPI 애플리케이션을 실행하는 ASGI 서버

# 기본: 단일 워커
uvicorn main:app --port 8000
 
# 다중 워커 (4개 프로세스)
uvicorn main:app --port 8000 --workers 4

또는 FastAPI의 run() 메서드:

fastapi run app/main.py --port 8000 --workers 4

프로덕션 배포

단계 1: Docker 컨테이너화

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["fastapi", "run", "app/main.py", "--port", "8000"]

단계 2: Traefik 리버스 프록시

  • HTTP(80) → Traefik
  • HTTPS(443) ← Let’s Encrypt 인증서
  • Traefik → FastAPI(8000) 라우팅

단계 3: 수평 확장

  • 여러 FastAPI 인스턴스 실행
  • Nginx로 로드 밸런싱

환경 설정

Pydantic Settings로 환경변수 관리:

from pydantic_settings import BaseSettings
 
class Settings(BaseSettings):
    database_url: str
    debug: bool = False
    
    class Config:
        env_file = ".env"
 
settings = Settings()

.env 파일 (git 무시):

DATABASE_URL=postgresql://user:pass@localhost:5432/db
DEBUG=False

관련 개념

관련 엔티티

  • uvicorn — ASGI 웹 서버
  • traefik — 리버스 프록시 (HTTPS/SSL)
  • docker — 컨테이너화

소스