본문 바로가기

Framework, Library/Fast api

[Fast_api] path parameters and Numeric validations

Query parameters에서 Query 와 같은 역할을 Path 가 해준다.

 

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")
):
    result = {"item_id": item_id}
    if q:
        result.update({"q": q})
    return result

다른 메타데이터의 역할을 크게 체감 못하고 있다..

 

숫자 범위 지정을 위한 검증을 해보자!

@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

위 코드는 0과 1000사이의 정수 item_id 조건을 걸어준다.

이때, 

  • g: greater
  • l: less
  • t: than
  • e: equal

똑같다. 뭐 문자 검증에서 숫자 검증으로 바뀐것뿐.

'Framework, Library > Fast api' 카테고리의 다른 글

[Fast api] Query Parameters and String Validations  (0) 2023.04.27
[Fast_api] Request Body  (0) 2023.04.27
[Fast_api] 쿼리 매개변수  (0) 2023.04.27
[Fast_api] 경로 매개변수  (0) 2023.04.27
[Fast_api] start  (0) 2023.04.27