Context

Python 코드 작업 중 Pydantic을 접하고 정확한 개념을 정리했다.

What I Learned

Pydantic은 Python에서 **데이터 검증(Validation)과 직렬화(Serialization)**를 위한 라이브러리다. 타입 힌트를 기반으로 런타임에 실제로 값을 검사한다.

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    age: int

user = User(id="123", name="Alice", age="25")
# → User(id=123, name='Alice', age=25)  # 자동 타입 변환

변환 불가능한 값은 생성 시점에 바로 에러:

User(id="abc", name="Alice", age="25")
# ValidationError: id - Input should be a valid integer

FastAPI에서의 역할

FastAPI는 사실상 Pydantic 위에서 돌아간다. 클라이언트 JSON을 받아 파싱 → 타입 검증 → Python 객체 생성까지 자동으로 처리한다.

class CreateUserRequest(BaseModel):
    email: str
    age: int

@app.post("/users")
async def create_user(req: CreateUserRequest):
    ...

Note

이름의 유래: Py(thon) + dantic(pedantic에서) — “꼼꼼하게 따지는”이라는 뜻. 데이터 검증 라이브러리 이름으로 딱 맞는 셈이다.

한 줄 요약: “Python 타입 힌트를 실제 런타임 검증 도구로 만들어 주는 라이브러리”

← All TIL