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
팁
가능하다면 Annotated가 달린 버전을 권장합니다.
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
팁
가능하다면 Annotated가 달린 버전을 권장합니다.
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 등) fastapi에서가 아닌 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
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
팁
가능하다면 Annotated가 달린 버전을 권장합니다.
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
팁
가능하다면 Annotated가 달린 버전을 권장합니다.
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 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 FieldInfo 클래스의 서브클래스입니다.
그리고 Pydantic의 Field 또한 FieldInfo의 인스턴스를 반환합니다.
Body 또한 FieldInfo의 서브클래스 객체를 직접적으로 반환합니다. 그리고 Body 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
Query, Path와 그 외 것들을 fastapi에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
팁
주목할 점은 타입, 기본 값 및 Field로 이루어진 각 모델 어트리뷰트가 Path, Query와 Body대신 Field를 사용하는 경로 작동 함수의 매개변수와 같은 구조를 가진다는 점 입니다.
Field, Query, Body, 그 외 안에 별도 정보를 선언할 수 있습니다. 이는 생성된 JSON 스키마에 포함됩니다.
여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다.
경고
별도 키가 전달된 Field 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
이런 키가 OpenAPI 명세서, the OpenAPI validator같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.