https://fastapi.tiangolo.com/tutorial/body-multiple-params/
Body - Multiple Parameters - FastAPI
Body - Multiple Parameters Now that we have seen how to use Path and Query, let's see more advanced uses of request body declarations. Mix Path, Query and body parameters First, of course, you can mix Path, Query and request body parameter declarations fre
fastapi.tiangolo.com
<FastAPI 공식문서 참조>
Path와 Query를 어떻게 이용하는지 알았으니까 이제 더 복잡한 request body 선언하는 법을 배워보자.
1. Path, Query, Body 매개변수 혼용
from typing import Annotated
from fastapi import FastAPI, Path
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str | None = None,
item: Item | None = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if item:
results.update({"item": item})
return results
위 코드에서,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str | None = None,
item: Item | None = None
이 부분이 혼용한 예시이다.
- path_parameter로 item_id 가,
- query_parameter로는 선택적 값(None)이,
- body_parameter로는 None으로 초기화된 Item 사용자 정의 객체가 들어간다.
2. Multiple body parameters
여러 개의 body가 매개변수로 들어갈 수도 있다. 아래 예시에서, item과 user라는 이름이 각각 Item과 User body와 매핑된다.
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
results = {"item_id": item_id, "item": item, "user": user}
return results
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
}
}
여러 개의 body를 매개변수로 받아도 FastAPI는 자동으로 해당하는 값을 찾아주며 새롭게 변경된 내용을 OpenAPI 스키마와 docs에 적용할 것이다.
3. Singular values in body
Query 및 Path에서 추가 데이터를 정의하는 기능을 Body에도 동등하게 제공한다.
그런데 값 하나만을 가지고 있는 Body를 추가할 때, 이를 Query parameter로 받아들일 수도 있다.
이때 아래의 코드를 이용해 Body로 규정할 수 있다.
@app.put("/items/{item_id}")
async def update_item(
item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
):
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
return results
item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
importance는 importance body를 찾아가는 key가 될 것이다.
request는 아래처럼 될 것이다.
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
},
"importance": 5
}
다중 Query 매개변수도 당연히 추가할 수 있다. Body인지 Query parameter인지 구분해서 사용만 하면 된다.
4. Embed a single body parameter
body parameter로 body를 받는데, 이때 매개변수의 이름을 key로 가지는 JSON 자체를 만들고 싶다면(그 내부의 모든 요소를 포함하는) 아래 키워드를 통해 구현할 수 있다.
Body(embed = True)
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
results = {"item_id": item_id, "item": item}
return results
이렇게 작성 시 FastAPI는 item이라는 Body를 다음과 같이 예상한다 :
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}
instead of :
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
5. 정리
단 하나의 값을 가지는 body도 여러 개 받을 수 있다. 그럴 때 자료형을 지정해주는 특수한 키워드를 사용해야 한다.
이 과정에서 FastAPI는 여러 정확성 확인에 관한 기능을 제공해 줄 것이다.
또한, 단 하나의 parameter만 존재해도 key가 body를 가지도록 mapping 해 줄 수 있다.
6. Reference
https://fastapi.tiangolo.com/tutorial/body-multiple-params/
Body - Multiple Parameters - FastAPI
Body - Multiple Parameters Now that we have seen how to use Path and Query, let's see more advanced uses of request body declarations. Mix Path, Query and body parameters First, of course, you can mix Path, Query and request body parameter declarations fre
fastapi.tiangolo.com
'프레임워크 > FastAPI' 카테고리의 다른 글
[FastAPI] FastAPI [8] Body - Nested Models (0) | 2023.03.28 |
---|---|
[FastAPI] FastAPI [7] Body - Fields (0) | 2023.03.27 |
[FastAPI] FastAPI [5] Path Parameters and Numeric Validations (0) | 2023.03.20 |
[FastAPI] FastAPI [4] Query Parameters and String Validations (0) | 2023.03.19 |
[FastAPI] FastAPI [3] - Request Body (0) | 2023.03.13 |