Перейти до змісту

Тіло — Поля

Так само як ви можете оголошувати додаткову валідацію та метадані в параметрах функції операції шляху за допомогою Query, Path та Body, ви можете оголошувати валідацію та метадані всередині моделей 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
🤓 Other versions and variants
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

Tip

Prefer to use the Annotated version if possible.

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

Tip

Prefer to use the Annotated version if possible.

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

Попередження

Зверніть увагу, що Field імпортується безпосередньо з pydantic, а не з fastapi, як усе інше (Query, Path, Body тощо).

Оголошення атрибутів моделі

Потім ви можете використовувати 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
🤓 Other versions and variants
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

Tip

Prefer to use the Annotated version if possible.

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

Tip

Prefer to use the Annotated version if possible.

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

Field працює так само, як Query, Path і Body, має ті самі параметри тощо.

Технічні деталі

Насправді Query, Path та інші, які ви побачите далі, створюють об'єкти підкласів спільного класу Param, який сам є підкласом класу FieldInfo з Pydantic.

І Field від Pydantic також повертає екземпляр FieldInfo.

Body також безпосередньо повертає об'єкти підкласу FieldInfo. І є інші, які ви побачите пізніше, що є підкласами класу Body.

Пам'ятайте, що коли ви імпортуєте Query, Path та інші з fastapi, це фактично функції, які повертають спеціальні класи.

Порада

Зверніть увагу, що кожен атрибут моделі з типом, значенням за замовчуванням і Field має ту саму структуру, що й параметр функції операції шляху, з Field замість Path, Query і Body.

Додавання додаткової інформації

Ви можете оголошувати додаткову інформацію в Field, Query, Body тощо. І вона буде включена до згенерованої JSON Schema.

Ви дізнаєтеся більше про додавання додаткової інформації пізніше в документації, коли вивчатимете, як оголошувати приклади.

Попередження

Додаткові ключі, передані в Field, також будуть присутні в отриманій схемі OpenAPI для вашого застосунку. Оскільки ці ключі не обов'язково є частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад валідатор OpenAPI, можуть не працювати з вашою згенерованою схемою.

Підсумок

Ви можете використовувати Field від Pydantic, щоб оголошувати додаткову валідацію та метадані для атрибутів моделі.

Ви також можете використовувати додаткові keyword arguments, щоб передавати додаткові метадані JSON Schema.