クエリパラメータ¶
パスパラメータの一部ではない他の関数パラメータを宣言すると、それらは自動的に「クエリ」パラメータとして解釈されます。
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]
クエリとは、URL 内の `?` の後に続く、`&` 文字で区切られたキーと値のペアのセットです。
たとえば、URL
http://127.0.0.1:8000/items/?skip=0&limit=10
...では、クエリパラメータは次のとおりです。
- `skip`:値は `0`
- `limit`:値は `10`
URL の一部であるため、「当然」文字列です。
しかし、Python の型(上記の例では `int`)で宣言すると、その型に変換され、その型に対して検証されます。
パスパラメータに適用されるすべてのプロセスは、クエリパラメータにも適用されます。
- エディタサポート(当然)
- データの「パース」(HTTP リクエストから送信された文字列を Python データに変換すること)
- データ検証
- 自動ドキュメント
デフォルト値¶
クエリパラメータはパスの固定部分ではないため、オプションで、デフォルト値を持つことができます。
上記の例では、デフォルト値は `skip=0` と `limit=10` です。
そのため、URL
http://127.0.0.1:8000/items/
にアクセスすることは、URL
http://127.0.0.1:8000/items/?skip=0&limit=10
にアクセスすることと同じです。
http://127.0.0.1:8000/items/?skip=20
しかし、たとえば、URL
- にアクセスすると、関数のパラメータ値は次のようになります。
- `skip=20`:URL で設定したため
`limit=10`:デフォルト値だったため
オプションパラメータ¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
Python 3.8+
この場合、関数パラメータ `q` はオプションとなり、デフォルトでは `None` になります。
確認
また、**FastAPI** は、パスパラメータ `item_id` がパスパラメータであり、`q` はそうでないためクエリパラメータであることを認識するほど賢いことにも注意してください。
クエリパラメータの型変換¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = 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
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = 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
`bool` 型も宣言でき、変換されます。
http://127.0.0.1:8000/items/foo?short=1
この場合、URL
http://127.0.0.1:8000/items/foo?short=True
この場合、URL
http://127.0.0.1:8000/items/foo?short=true
この場合、URL
http://127.0.0.1:8000/items/foo?short=on
この場合、URL
http://127.0.0.1:8000/items/foo?short=yes
または
、またはその他のバリエーション(大文字、先頭文字を大文字にするなど)にアクセスすると、関数はパラメータ `short` を `bool` 値 `True` として認識します。そうでない場合は `False` です。
複数のパスパラメータとクエリパラメータ¶
複数のパスパラメータとクエリパラメータを同時に宣言できます。**FastAPI** はどちらがどちらかを認識します。
また、特定の順序で宣言する必要はありません。
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str | None = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_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
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_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
必須クエリパラメータ¶
パス以外の パラメータ(今のところ、クエリパラメータのみ)にデフォルト値を宣言すると、必須ではなくなります。
特定の値を追加したくないが、オプションにしたい場合は、デフォルトを None
に設定します。
クエリパラメータを必須にしたい場合は、デフォルト値を宣言しないだけです。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):
item = {"item_id": item_id, "needy": needy}
return item
ここで、クエリパラメータ needy
は、str
型の必須クエリパラメータです。
ブラウザで次のような URL を開くと
http://127.0.0.1:8000/items/foo-item
...必須パラメータ needy
を追加しないと、次のようなエラーが表示されます。
{
"detail": [
{
"type": "missing",
"loc": [
"query",
"needy"
],
"msg": "Field required",
"input": null,
"url": "https://errors.pydantic.dev/2.1/v/missing"
}
]
}
needy
は必須パラメータなので、URL に設定する必要があります。
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
...これは動作します。
{
"item_id": "foo-item",
"needy": "sooooneedy"
}
もちろん、必須のパラメータ、デフォルト値を持つパラメータ、完全にオプションのパラメータを定義できます。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(
item_id: str, needy: str, skip: int = 0, limit: int | None = None
):
item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
return item
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(
item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
):
item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
return item
この場合、3 つのクエリパラメータがあります。
needy
、必須のstr
。skip
、デフォルト値が0
のint
。limit
、オプションのint
。
ヒント
パス パラメータと同様に、Enum
を使用することもできます。