함수 파라미터에 path에 정의되지 않은 변수를 정의할 경우, 이는 Query Parameter로 인식이 된다.

쿼리는 key-value 형식으로 되고, URL뒤에 ?이 붙고 적히며, 여러개일 경우 &으로 이어진다.

<http://127.0.0.1:8000/items/?skip=0&limit=10>
from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

Optional Parameters

같은 방법으로 Optional Query Parameter를 작성할 수 있다. Default로 None으로 설정한다.

from typing import Optional

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

q가 optional 파라미터이며, None을 Default로 받는다.

만약 qOptional이 아닌 str형식과 Default 값을 정의하지 않으면 Required Query Parameter로 인식이 되어 반드시 URL에 명시를 해주어야한다.

만약 없을 경우 아래와 같은 error을 반환한다.

{
    "detail": [
        {
            "loc": [
                "query",
                "q"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

Query Parameter Type Conversion

Query parameter는 Type에 따라 값이 바뀔 수 있다.

from typing import Optional

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

short 파라미터는 bool 타입으로 선언되어있다. 이 경우 shortTrueFalse 값으로 값이 자동 변환 된다.

<http://127.0.0.1:8000/items/foo?short=1>
<http://127.0.0.1:8000/items/foo?short=True>
<http://127.0.0.1:8000/items/foo?short=true>
<http://127.0.0.1:8000/items/foo?short=on>
<http://127.0.0.1:8000/items/foo?short=yes>

위의 경우는 모두 True로 Converting 되는 경우를 나타낸다. 즉, False0과 같은 정확한 명시가 없고, 다른 데이터가 들어가면 원래의 Python에서 그렇듯 True로 인식한다.