3. Pydantic 으로 Request Body 다루기

# 3 강. Pydantic 으로 Request Body 다루기 ## 🎯 학습 목표 - Pydantic 모델 정의하기 - JSON Request Body 수신하기 - 자동 유효성 검사 --- ## 1. Pydantic 모델 정의 ```python from pydantic import BaseModel class Item(BaseModel): name: str price: float description: str | None = None ``` --- ## 2. 사용법 ```python from fastapi import FastAPI app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items/") def create_item(item: Item): return item ``` **요청 예시:** ```json { "name": "Laptop", "price": 999.99 } ``` --- ## 3. Field() 로 상세 검증 ```python from pydantic import BaseModel, Field class UserCreate(BaseModel): username: str = Field(..., min_length=3, max_length=20) email: str = Field(..., pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$") password: str = Field(..., min_length=8) age: int = Field(..., ge=1, le=150) ```