[FastAPI] 중첩된 JSON 모델(Nested JSON Models) 사용
2023. 9. 25. 14:06
class ListStr(BaseModel):
strings: List[str]
@app.post('/listTest')
def listTest(strings_input:ListStr):
s = strings_input.strings
ListStr 모델의 요청 데이터가 바로 JSON 배열
- Fastapi가 'strings'필드에 매핑
- 따라서 'strings'필드에 대한 리스트로 데이터를 사용할 수 있음
# 요청 JSON
{
"strings": ["문자열1", "문자열2", "문자열3"]
}
{
"result": [
"문자열1",
"문자열2",
"문자열3"
]
}
class ListStr(BaseModel):
strings: List[str]
class OtherOptions(BaseModel):
a: Optional[str]
b: Optional[float]
@app.post('/listTest')
def listTest(strings_input:ListStr, other_input:OtherOptions):
s = strings_input.strings
o = other_input
잘못된 JSON 요청
- 'ListStr' 모델과 'OtherOptions'모델을 동시에 사용
- 'strings_input'와 'other_input'는 두 개의 서로 다른 JSON 객체
- 'strings_input'는 'strings' 필드 하나를 가지고 있는 JSON 객체이며,
'OptherOptions'는 'a', 'b' 필드를 가지고 있는 JSON 객체
# 요청 JSON
{
"strings_input": ["문자열1", "문자열2", "문자열3"],
"other_input":{"a":"a", "b":2}
}
{
"detail": [
{
"type": "model_attributes_type",
"loc": [
"body",
"strings_input"
],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": [
"문자열1",
"문자열2",
"문자열3"
],
}
]
}
올바른 JSON 요청
- FastAPI는 이러한 JSON 객체의 구조를 정확하게 매핑하기 위해 모델을 사용함
- 따라서 'strings_input'과 'other_option'을 각각의 모델에 매핑하려면 요청 데이터를 해당 구조에 따라 정확하게 구성해야 함
- 'strings_input'과 'other_option'을 JSON 객체로 감싸서 전달해야 함
- 이렇게 하면 FastAPI가 요청 데이터를 'ListStr'과 'OtherOptions' 모델에 각각 매핑할 수 있음
# 요청 JSON
{
"strings_input": {
"strings":["문자열1", "문자열2", "문자열3"]
},
"other_option": {
"a": "a",
"b": 2
}
}
'WebFramework > [FastAPI]' 카테고리의 다른 글
[FastAPI] room 기능 구현 및 worker간 공유 (RabbitMQ) (0) | 2024.01.24 |
---|---|
[FastAPI] SocketIO 마운트해서 사용하기 (0) | 2024.01.24 |
[FastAPI] BackgroundTasks, Celery (0) | 2024.01.09 |
[FastAPI] SQLAlchemy 요소 (0) | 2023.08.08 |
[wsl] 파이썬 가상환경 진입 bash 사용 (0) | 2023.03.10 |