Fast API 사용해보기 - Path Parameters and Numeric Validations

JinWooHyun·2021년 8월 20일
0

Fast API 프로젝트

목록 보기
6/6

이전 장에서 Query를 이용해 query parameter에 대해 검증이나 추가 정보를 선언한 것처럼 Path를 이용해 path parameter에 대해서도 동일한 작업을 할 수 있습니다.

from typing import Optional
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: Optional[str] = Query(None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

path parameter는 URL의 일부이기 때문에 항상 required 합니다. 그래서 필수로 표시하려면 ... 로 선언해야 합니다. 기본 값을 None으로 선언하거나 다른 값을 설정하더라도 영향을 끼치진 않고 여전히 required한 상태입니다.

FastAPI에서는 파라미터를 이름으로 구분하기 때문에 타입이나 기본 선언(Query, Path)의 순서는 중요하지 않습니다.

from fastapi import FastAPI, Path

app = FastAPI()

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

QueryPath를 이용하여 string 제약도 할 수 있지만, number 제약도 가능합니다.

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", ge=1), q: str

):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
  • ge : greater than equal
  • le : less than or equal
  • gt : greater than
  • lt : less than
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
profile
Unicorn Developer

0개의 댓글