본문 바로가기

Programming/[Python]

[FastAPI] 3. pydantic 모델을 사용한 요청 바디 검증

반응형

참고 도서

 

개발환경 : WSL2 (Ubuntu 20.04), Python 3.10 (anaconda 가상환경)

 

 

pydantic 모델을 사용한 요청 바디 검증

  • FastAPI에서는 정의된 데이터만 전송되도록 요청 바디를 검증할 수 있음. (매우 중요한 기능!!)

다음은 model.py 작성 코드이다. 

from pydantic import BaseModel

class Todo(BaseModel):
    id: int
    item: str

이 코드는 다음 두 개의 필드만 허용하는 pydantic 모델을 만든다.

  • 정수형(int)인 id
  • 문자열형(str)인 item

이 모델을 POST 라우트에 사용해보자. todo.py 파일에 다음과 같이 모델을 임포트 한다.

from fastapi import APIRouter
from model import Todo	# 추가

todo_router = APIRouter()

todo_list = []

@todo_router.post("/todo")
async def add_todo(todo: Todo) -> dict:	# 수정
    todo_list.append(todo)
    return {
        "메시지" : "Todo가 추가되었습니다."
    }

@todo_router.get("/todo")
async def retrieve_todos() -> dict:
    return {
        "todo" : todo_list
    }

 

빈 딕셔너리를 요청 바디로 보내서 모델이 제대로 검증되는지 확인함.

Linux

curl -X 'POST' \
'http://127.0.0.1:8000/todo' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{}'

Windows

curl -X POST http://127.0.0.1:8000/todo -H "accept: application/json" -H "Content-Type: application/json" -d "{}"

명령을 실행하면 다음과 같이 요청 바디에 id와 item이 없다는 오류 메시지가 출력됨.

{
    "detail":[
        {
            "type":"missing",
            "loc":[
                "body",
                "id"
                ],
            "msg":"Field required",
            "input":{},
            "url":"https://errors.pydantic.dev/2.1/v/missing"
        },
        {
            "type":"missing",
            "loc":[
                "body",
                "item"
                ],
            "msg":"Field required",
            "input":{},
            "url":"https://errors.pydantic.dev/2.1/v/missing"
        }
    ]
}

 

모델과 일치하는 데이터를 전송해보자.

 

Linux

curl -X 'POST' \
'http://127.0.0.1:8000/todo' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"id":2,
"item": "Validation models help with input types"
}'

Windows

curl -X POST http://127.0.0.1:8000/todo -H "accept: application/json" -H "Content-Type: application/json" -d "{\"id\":2, \"item\":\"Validation models help with input types\"}"

결과

{"메시지":"Todo가 추가되었습니다."}

 

중첩 모델

pydantic 모델은 다음과 같이 중첩해서 정의할 수 있다.

from pydantic import BaseModel

class Item(BaseModel):
    item: str
    status: str

class Todo(BaseModel):
    id: int
    item: Item

 

결과적으로 Todo형의 데이터는 다음과 같이 표현된다.

{
    "id": 1,
    "item": {
        "item": "중첩 모델",
        "status": "완료"
    }
}

 

반응형