Query를 사용하여 쿼리 매개변수에 대해서 많은 유효성 검사 및 메타데이터를 선언 한것과 같이, Path를 사용하여 경로 매개변수에 대해 유효성 검사 및 메타데이터를 선언할수 있다.
from typing import Union
from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")],
q: Annotated[Union[str, None], Query(alias="item-query")] = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
매개변수에 *를 사용하게 되면 그 뒤에 오게되는 모든 매개변수들이 키워드 전용 매개변수임을 알려줍니다.
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
위와 같이 구성이 되어있을때 * 표시가 있는것을 보고, 키워드 전용 매개변수가 모두 온다라고 생각하면됩니다.
ge = 1을사용하여 path파라미터에 오는 숫자의 값을 1이상으로 설정할 수 있다.
from fastapi import FastAPI, Path
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
만약에 ge=1 을 설정한 상태에서 0을 입력하게 되면 아래와 같이 결과를 보게된다.
le파라미터를 활용하여 특정숫자 이하로 설정할 수 있다.
float형태의 경우 gt와 it로 설정이 가능합니다.
int 형의 경우 le, ge 즉, 높거나 낮거나 같은것
float형의 경우 lt, gt 즉, 높거나 낮은것 으로 설정할 수 있습니다.
from fastapi import FastAPI, Path, Query
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: str,
size: Annotated[float, Query(gt=0, lt=10.5)],
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
Query와 Path를 사용하여 쿼리 혹은 경로 매개변수에 대해서 유효성검사와 메타데이터를 선언할 수 있습니다.