에듀테크 프로젝트 대시보드
요청 본문 (Request Body)
Pydantic 모델 타입을 인자로 선언하면 요청 본문(JSON)을 파싱·검증해 객체로 넣어줍니다.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
tax: float | None = None
@app.post("/items")
def create_item(item: Item):
total = item.price + (item.tax or 0)
return {"name": item.name, "total": total}{
"name": "연필",
"price": 500
}@app.put("/items/{item_id}")
def update(item_id: int, item: Item, notify: bool = False):
# item_id -> 경로, notify -> 쿼리, item -> 본문
...class User(BaseModel):
username: str
@app.post("/orders")
def create(item: Item, user: User):
...
# 본문이 키로 감싸짐:
# {"item": {...}, "user": {...}}from typing import Annotated
from fastapi import Body
@app.post("/items")
def create(item: Annotated[Item, Body(embed=True)]):
...
# 기대 본문: {"item": {"name": ..., "price": ...}}@app.post("/items/{id}/rate")
def rate(id: int, score: Annotated[int, Body(ge=1, le=5)]):
...
# 본문: {"score": 4}