경로 매개 변수에서의 유효성 검증
경로 매개 변수에서 유효성을 검증하려고 한다면 Path을 이용하여 처리 할 수 있다.
Path는 fastapi 패키지에 있기 때문에 import 해서 사용한다.
from typing import Union
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: int = Path(title="The ID of the item to get"),
q: Union[str, None] = Query(default=None, alias="item-query"),
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
Path에서 함께 사용한 옵션 인자로는 아래가 있다.
- gt: 크거나(greater than)
- ge: 크거나 같은(greater than or equal)
- lt: 작거나(less than)
- le: 작거나 같은(less than or equal)
예)
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
*,
item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
q: str,
size: float = Query(gt=0, lt=10.5),
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
'FrameWork > Fastapi' 카테고리의 다른 글
[Fastapi] Body Fields을 통한 유효성 검증, 중첩 모델 (0) | 2023.05.12 |
---|---|
[Fastapi] Body Multiple Parameters (0) | 2023.05.12 |
[Fastapi] 유효성 검사, 필수 매개변수, 쿼리 매개변수 목록/다중 값 처리 (0) | 2023.05.12 |
[Fastapi] 요청 본문 (0) | 2023.05.12 |
[Fastapi] 쿼리 매개변수와 열거체(Enum) 처리 (0) | 2023.05.12 |