시작과 요청 단원 · 5개 유형 FastAPI 전체 29개 ›
FastAPI 시작하기첫 번째 앱경로 매개변수쿼리 매개변수요청 본문

요청 본문 (Request Body)

BaseModel JSON body 다중 본문 embed

Pydantic 모델 타입을 인자로 선언하면 요청 본문(JSON)을 파싱·검증해 객체로 넣어줍니다.

1. 모델로 본문 받기

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
}

2. 경로 + 쿼리 + 본문 동시에

@app.put("/items/{item_id}")
def update(item_id: int, item: Item, notify: bool = False):
    # item_id -> 경로,  notify -> 쿼리,  item -> 본문
    ...

3. 여러 모델을 본문으로

class User(BaseModel):
    username: str

@app.post("/orders")
def create(item: Item, user: User):
    ...

# 본문이 키로 감싸짐:
# {"item": {...}, "user": {...}}

4. 단일 모델도 키로 감싸기 (embed)

from typing import Annotated
from fastapi import Body

@app.post("/items")
def create(item: Annotated[Item, Body(embed=True)]):
    ...
# 기대 본문: {"item": {"name": ..., "price": ...}}

5. 단일 스칼라 값을 본문으로

@app.post("/items/{id}/rate")
def rate(id: int, score: Annotated[int, Body(ge=1, le=5)]):
    ...
# 본문: {"score": 4}
"커넥션은 요청마다 열지 말고 풀에서 빌려 쓴다"

FastAPI 전체 29개

단원별로 배우는 순서대로 모았습니다.