So wie Sie zusätzliche Validation und Metadaten in Parametern der Pfadoperation-Funktion mittels Query, Path und Body deklarieren, können Sie auch innerhalb von Pydantic-Modellen zusätzliche Validation und Metadaten deklarieren, mittels Pydantics 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
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
Tipp
Bevorzugen Sie die Annotated-Version, falls möglich.
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
Tipp
Bevorzugen Sie die Annotated-Version, falls möglich.
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
Achtung
Beachten Sie, dass Field direkt von pydantic importiert wird, nicht von fastapi, wie die anderen (Query, Path, Body, usw.)
Dann können Sie Field mit Modellattributen deklarieren:
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
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
Tipp
Bevorzugen Sie die Annotated-Version, falls möglich.
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
Tipp
Bevorzugen Sie die Annotated-Version, falls möglich.
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 funktioniert genauso wie Query, Path und Body, es hat die gleichen Parameter, usw.
Technische Details
Tatsächlich erstellen Query, Path und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse Param, die ihrerseits eine Unterklasse von Pydantics FieldInfo-Klasse ist.
Und Pydantics Field gibt ebenfalls eine Instanz von FieldInfo zurück.
Body gibt auch Instanzen einer Unterklasse von FieldInfo zurück. Und später werden Sie andere sehen, die Unterklassen der Body-Klasse sind.
Denken Sie daran, dass Query, Path und andere von fastapi tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
Tipp
Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und Field die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit Field statt Path, Query, Body.
Sie können zusätzliche Information in Field, Query, Body, usw. deklarieren. Und es wird im generierten JSON-Schema untergebracht.
Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
Achtung
Extra-Schlüssel, die Field überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa der OpenAPI-Validator, nicht mit Ihrem generierten Schema funktionieren.