Так само як ви можете визначати додаткову валідацію та метадані у параметрах функції обробки шляху за допомогою Query, Path та Body, ви можете визначати валідацію та метадані всередині моделей Pydantic за допомогою Field від Pydantic.
fromtypingimportAnnotatedfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
🤓 Other versions and variants
fromtypingimportAnnotated,UnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
fromtypingimportUnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldfromtyping_extensionsimportAnnotatedapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
Tip
Prefer to use the Annotated version if possible.
fromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Item=Body(embed=True)):results={"item_id":item_id,"item":item}returnresults
Tip
Prefer to use the Annotated version if possible.
fromtypingimportUnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Item=Body(embed=True)):results={"item_id":item_id,"item":item}returnresults
Warning
Зверніть увагу, що Field імпортується прямо з pydantic, а не з fastapi, як всі інші (Query, Path, Body тощо).
Ви можете використовувати Field з атрибутами моделі:
fromtypingimportAnnotatedfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
🤓 Other versions and variants
fromtypingimportAnnotated,UnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
fromtypingimportUnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldfromtyping_extensionsimportAnnotatedapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(embed=True)]):results={"item_id":item_id,"item":item}returnresults
Tip
Prefer to use the Annotated version if possible.
fromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Item=Body(embed=True)):results={"item_id":item_id,"item":item}returnresults
Tip
Prefer to use the Annotated version if possible.
fromtypingimportUnionfromfastapiimportBody,FastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:strdescription: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}")asyncdefupdate_item(item_id:int,item:Item=Body(embed=True)):results={"item_id":item_id,"item":item}returnresults
Field працює так само, як Query, Path і Body, у нього такі самі параметри тощо.
Технічні деталі
Насправді, Query, Path та інші, що ви побачите далі, створюють об'єкти підкласів загального класу Param, котрий сам є підкласом класу FieldInfo з Pydantic.
І Field від Pydantic також повертає екземпляр FieldInfo.
Body також безпосередньо повертає об'єкти підкласу FieldInfo. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
Tip
Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та Field має ту саму структуру, що й параметр функції обробки шляху, з Field замість Path, Query і Body.
Ви можете визначити додаткову інформацію у Field, Query, Body тощо. І вона буде включена у згенеровану JSON схему.
Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів.
Warning
Додаткові ключі, передані в Field, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка.
Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, OpenAPI валідатор, можуть не працювати з вашою згенерованою схемою.