fromdataclassesimportdataclass,fieldfromtypingimportList,UnionfromfastapiimportFastAPI@dataclassclassItem:name:strprice:floattags:List[str]=field(default_factory=list)description:Union[str,None]=Nonetax:Union[float,None]=Noneapp=FastAPI()@app.get("/items/next",response_model=Item)asyncdefread_next_item():return{"name":"Island In The Moon","price":12.99,"description":"A place to be be playin' and havin' fun","tags":["breater"],}
还有一些情况也可以使用 Pydantic 的 dataclasses。例如,在 API 文档中显示错误。
本例把标准的 dataclasses 直接替换为 pydantic.dataclasses:
fromdataclassesimportfield# fromtypingimportList,UnionfromfastapiimportFastAPIfrompydantic.dataclassesimportdataclass# @dataclassclassItem:name:strdescription:Union[str,None]=None@dataclassclassAuthor:name:stritems:List[Item]=field(default_factory=list)# app=FastAPI()@app.post("/authors/{author_id}/items/",response_model=Author)# asyncdefcreate_author_items(author_id:str,items:List[Item]):# return{"name":author_id,"items":items}# @app.get("/authors/",response_model=List[Author])# defget_authors():# return[# {"name":"Breaters","items":[{"name":"Island In The Moon","description":"A place to be be playin' and havin' fun",},{"name":"Holy Buddies"},],},{"name":"System of an Up","items":[{"name":"Salt","description":"The kombucha mushroom people's favorite",},{"name":"Pad Thai"},{"name":"Lonely Night","description":"The mostests lonliest nightiest of allest",},],},]