Using Dataclasses¶
FastAPI is built on top ofPydantic, and I have been showing you how to use Pydantic models to declare requests and responses.
But FastAPI also supports usingdataclasses the same way:
fromdataclassesimportdataclassfromfastapiimportFastAPI@dataclassclassItem:name:strprice:floatdescription:str|None=Nonetax:float|None=Noneapp=FastAPI()@app.post("/items/")asyncdefcreate_item(item:Item):returnitemThis is still supported thanks toPydantic, as it hasinternal support fordataclasses.
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
And of course, it supports the same:
- data validation
- data serialization
- data documentation, etc.
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
Info
Keep in mind that dataclasses can't do everything Pydantic models can do.
So, you might still need to use Pydantic models.
But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
Dataclasses inresponse_model¶
You can also usedataclasses in theresponse_model parameter:
fromdataclassesimportdataclass,fieldfromfastapiimportFastAPI@dataclassclassItem:name:strprice:floattags:list[str]=field(default_factory=list)description:str|None=Nonetax: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 playin' and havin' fun","tags":["breater"],}The dataclass will be automatically converted to a Pydantic dataclass.
This way, its schema will show up in the API docs user interface:

Dataclasses in Nested Data Structures¶
You can also combinedataclasses with other type annotations to make nested data structures.
In some cases, you might still have to use Pydantic's version ofdataclasses. For example, if you have errors with the automatically generated API documentation.
In that case, you can simply swap the standarddataclasses withpydantic.dataclasses, which is a drop-in replacement:
fromdataclassesimportfield# (1)fromfastapiimportFastAPIfrompydantic.dataclassesimportdataclass# (2)@dataclassclassItem:name:strdescription:str|None=None@dataclassclassAuthor:name:stritems:list[Item]=field(default_factory=list)# (3)app=FastAPI()@app.post("/authors/{author_id}/items/",response_model=Author)# (4)asyncdefcreate_author_items(author_id:str,items:list[Item]):# (5)return{"name":author_id,"items":items}# (6)@app.get("/authors/",response_model=list[Author])# (7)defget_authors():# (8)return[# (9){"name":"Breaters","items":[{"name":"Island In The Moon","description":"A place to 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",},],},]We still import
fieldfrom standarddataclasses.pydantic.dataclassesis a drop-in replacement fordataclasses.The
Authordataclass includes a list ofItemdataclasses.The
Authordataclass is used as theresponse_modelparameter.You can use other standard type annotations with dataclasses as the request body.
In this case, it's a list of
Itemdataclasses.Here we are returning a dictionary that contains
itemswhich is a list of dataclasses.FastAPI is still capable ofserializing the data to JSON.
Here the
response_modelis using a type annotation of a list ofAuthordataclasses.Again, you can combine
dataclasseswith standard type annotations.Notice that thispath operation function uses regular
definstead ofasync def.As always, in FastAPI you can combine
defandasync defas needed.If you need a refresher about when to use which, check out the section"In a hurry?" in the docs about
asyncandawait.Thispath operation function is not returning dataclasses (although it could), but a list of dictionaries with internal data.
FastAPI will use the
response_modelparameter (that includes dataclasses) to convert the response.
You can combinedataclasses with other type annotations in many different combinations to form complex data structures.
Check the in-code annotation tips above to see more specific details.
Learn More¶
You can also combinedataclasses with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check thePydantic docs about dataclasses.
Version¶
This is available since FastAPI version0.67.0. 🔖







