Using Dataclasses
The current page still doesn’t have a translation for this language.
But you can help translating it: Contributing.
FastAPI is built on top of Pydantic, and I have been showing you how to use Pydantic models to declare requests and responses.
But FastAPI also supports using the same way:
This is still supported thanks to Pydantic, as it has internal support for dataclasses.
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 documentation, etc.
Info
Have 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. 🤓
You can also use dataclasses
in the parameter:
The dataclass will be automatically converted to a Pydantic dataclass.
This way, its schema will show up in the API docs user interface:
You can also combine dataclasses
with other type annotations to make nested data structures.
In some cases, you might still have to use Pydantic’s version of dataclasses
. For example, if you have errors with the automatically generated API documentation.
In that case, you can simply swap the standard with pydantic.dataclasses
, which is a drop-in replacement:
You can combine dataclasses
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.
You can also combine with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check the Pydantic docs about dataclasses.