コンテンツへスキップ

クエリパラメータ

パスパラメータの一部ではない他の関数パラメータを宣言すると、それらは自動的に「クエリ」パラメータとして解釈されます。

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)で宣言すると、その型に変換され、それに照らして検証されます。

パスパラメータに適用されたのと同じプロセスが、クエリパラメータにも適用されます。

  • エディタのサポート(当然)
  • データ 「解析」
  • データ検証
  • 自動ドキュメント

デフォルト

クエリパラメータはパスの固定部分ではないため、オプションにでき、デフォルト値を設定できます。

上記の例では、skip=0limit=10のデフォルト値が設定されています。

したがって、URLにアクセスする

http://127.0.0.1:8000/items/

にアクセスするのと同じです。

http://127.0.0.1:8000/items/?skip=0&limit=10

しかし、例えば、にアクセスすると

http://127.0.0.1:8000/items/?skip=20

関数内のパラメータ値は次のようになります。

  • skip=20: URLで設定したため
  • limit=10: デフォルト値であったため

オプションパラメータ

同様に、デフォルトをNoneに設定することで、オプションのクエリパラメータを宣言できます。

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}

この場合、関数パラメータqはオプションになり、デフォルトでNoneになります。

確認

また、FastAPIは、パスパラメータitem_idがパスパラメータであり、qがそうではないことを認識するのに十分スマートであることにも注意してください。そのため、qはクエリパラメータです。

クエリパラメータの型変換

bool型も宣言でき、それらは変換されます。

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

この場合、にアクセスすると

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

またはその他の大文字小文字のバリエーション(大文字、先頭文字が大文字など)では、関数はパラメータshortTruebool値として認識します。それ以外の場合は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、デフォルト値が0int
  • limit、オプションのint

ヒント

パスパラメータと同様に、Enumを使用することもできます。