コンテンツへスキップ

Body - フィールド

パス操作関数のパラメータでQueryPathBodyを使って追加の検証とメタデータを宣言するのと同じように、PydanticのFieldを使ってPydanticモデル内に検証とメタデータを宣言できます。

Fieldをインポートする

まず、インポートする必要があります

from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
🤓 その他のバージョンとバリアント
from typing import Annotated, Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
from typing import Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
from typing_extensions import Annotated

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results

ヒント

可能であれば`Annotated`バージョンを使用することをお勧めします。

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

ヒント

可能であれば`Annotated`バージョンを使用することをお勧めします。

from typing import Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

Warning

Fieldは、他のすべて(QueryPathBodyなど)がfastapiからインポートされるのとは異なり、pydanticから直接インポートされることに注意してください。

モデルの属性を宣言する

その後、Fieldをモデルの属性とともに使用できます

from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
🤓 その他のバージョンとバリアント
from typing import Annotated, Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
from typing import Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
from typing_extensions import Annotated

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results

ヒント

可能であれば`Annotated`バージョンを使用することをお勧めします。

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

ヒント

可能であれば`Annotated`バージョンを使用することをお勧めします。

from typing import Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = Field(
        default=None, title="The description of the item", max_length=300
    )
    price: float = Field(gt=0, description="The price must be greater than zero")
    tax: Union[float, None] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

FieldQueryPathBodyと同じように機能し、同じパラメータをすべて持ちます。

技術的な詳細

実際、QueryPath、および次に説明する他のものは、共通のParamクラスのサブクラスのオブジェクトを作成します。これは、PydanticのFieldInfoクラスのサブクラスです。

そして、PydanticのFieldFieldInfoのインスタンスを返します。

Bodyもまた、FieldInfoのサブクラスのオブジェクトを直接返します。そして、後で説明するBodyクラスのサブクラスである他のものもあります。

fastapiからQueryPath、その他をインポートするとき、それらは実際には特殊なクラスを返す関数であることを忘れないでください。

ヒント

型、デフォルト値、およびFieldを持つ各モデルの属性が、PathQueryBodyの代わりにFieldを使用するパス操作関数のパラメータと同じ構造を持っていることに注目してください。

追加情報を追加する

FieldQueryBodyなどで追加情報を宣言でき、生成されたJSON Schemaに含まれます。

例を宣言する方法を学ぶ際に、ドキュメントの後半で追加情報の追加について詳しく学びます。

Warning

Fieldに渡された追加のキーも、アプリケーションのOpenAPIスキーマに表示されます。これらのキーは必ずしもOpenAPI仕様の一部ではないため、一部のOpenAPIツール、例えばOpenAPIバリデーターは、生成されたスキーマで機能しない可能性があります。

まとめ

PydanticのFieldを使用して、モデル属性の追加の検証とメタデータを宣言できます。

追加のキーワード引数を使用して、追加のJSON Schemaメタデータを渡すこともできます。