더북(TheBook)

hello_fastapi/main.py

from fastapi import FastAPI
from pydantic import BaseModel 
(중략)

# 쿼리 파라미터 사용
@app.get("/items")
def read_items_handler(max_price: int | None = None):
    return {"max_price": max_price}

# 아이템 모델 정의 
class Item(BaseModel): # ➊ 요청 본문 검증을 위한 Item 모델 정의
    name: str
    price: int
    in_stock: bool = True

# 새 아이템 등록
@app.post("/items")   # ➋ POST 요청과 경로 매핑 설정
def create_item_handler(item: Item): # ➌ 요청 본문 데이터를 Item 객체로 변환
    return {"message": f"아이템 '{item.name}'이(가) 추가되었습니다.", "item": item}