-
FastAPI - Body (다중 매개변수, 필드, 중첩 모델)Backend 2025. 10. 25. 22:36
I. 다중 매개변수
Path와 Query 사용법에 대한 설명.
- Path, Query 및 요청 본문 매개변수 혼합 가능
- 다중 본문 매개변수:
async def lab(item: Item, user: User):와 같이 선언 가능.
-> 함수 안에 한 개 이상의 본문 매개변수이므로 본문의 매개변수 이름을 key (Field name)으로 설정 가능.
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }, "user": { "username": "dave", "full_name": "Dave Grohl" } }- 본문 내의 단일 값: FastAPI는 동등한 Body 제공, 단일값을 선언하면 쿼리 매개변수로 가정되나 Body를 이용하면 다른 본문 키로 처리.
*Query vs Body: Query는 ? 뒤의 값 (URL에 포함) / Body는 HTTP 요청 본문 값 (URL에 포함되지 않음)
@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item, user: User, importance: int = Body()): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} return results와 같이 importance를 Body로 명시하면,
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }, "user": { "username": "dave", "full_name": "Dave Grohl" }, "importance": 5 }FastAPI는 본문을 위와 같이 이해.
- 다중 본문 매개변수와 쿼리: 기본적으로 단일 값은 쿼리 매개변수 -> Query 명시적으로 추가 필요 없음
- 단일본문 매개변수 삽입
Pydantic model Item의 item을 body param으로 하나만 있으면 본문으로 인식
모델 내용에 item 키 가진 JSON으로 인식 원하면 Body의 매개변수 embed 사용.
item: Item일시,
{ "name": "Apple", "price": 3.5 }하지만 item: Item = Body(embed=True) 일시,
{ "item": { "name": "Apple", "price": 3.5 } }본문 내용을 item이 감싼다
II. 필드
- Field로 검증 및 메타데이터 선언 가능
- Model Attribute: Field 사용
description: str | None = Field( default=None, title="The description of the item", max_length=300 ) price: float = Field(gt=0, description="The price must be greater than zero")*BaseModel 내부
- Field, Query, Body 등에 별도 정보 선언 가능 (JSON schema에 포함)
III. 중첩 모델
- 리스트 필드: Attribute를 subtype로 지정 가능 (tags: list = [])
- Type param 있는 리스트 필드
a. list, dict, tuple과 같은 타입 매개변수 타입 선언: typing 모듈에서 임포트 -> List[str]처럼 내부 타입 전달
class Item(BaseModel): name: str tags: List[str] = []- 집합 타입
tags: Set[str] = set()a. 중복 데이터 있는 요청 수신해도 고유 항목 집합으로 변환
- 중첩 모델
-> Pydantic의 Attribute들은 타입 자체로 또다른 pydantic 모델의 타입이 될 수 있음 (다른 BaseModel이 타입이 될 수 있다)
-> Submodel 정의 & Submodel을 type으로 사용
class Image(BaseModel): url: str name: str class Item(BaseModel): name: str description: Union[str, None] = None image: Union[Image, None] = None그러면 아래와 같은 본문:
{ "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2, "tags": ["rock", "metal", "bar"], "image": { "url": "http://example.com/baz.jpg", "name": "The Foo live" } }- 특별한 타입과 검증: str을 상속하는 더 복잡한 단일 타입 사용 가능
-> 예: url을 str 대신 HttpUrl로 선언 가능
- Submodel list 갖는 어트리뷰트: list, set 등의 subtype으로 pydantic 모델 사용
images: Union[List[Image], None] = None- 깊이 중첩된 모델: 연쇄적으로 어트리뷰트를 타입으로 갖다쓰기
- 순수 리스트의 본문: 예상되는 JSON 본문의 최상위 값이 JSON array (python list) 이면 함수의 매개면수에서 타입 선언 가능
class Image(BaseModel): url: HttpUrl name: str @app.post("/images/multiple/") async def create_multiple_images(images: List[Image]): return images(여기서 pydantic List 대신 python list도 가능)
- 단독 dict의 본문: 일부 타입의 키와 다른 타입의 값을 사용해 dict로 본문 선언 (유효한 필드, 어트리뷰트 이름 몰라도 됨)
'Backend' 카테고리의 다른 글
FastAPI - 요청 본문, 검증, Pydantic (쿼리) (0) 2025.10.21 FastAPI - 매개변수 (0) 2025.10.16