Building async repository for FastAPI using ODMantic
The dependencies of Beanie and ODMantic come from Motor and Pydantic. ODMantic also utilizes Motor’s AsyncIOMotorClient
class to open a database connection. It also uses Pydantic features for class attribute validation, Python’s typing extension for type hinting, and other Python components for management. But its edge over Beanie is that it complies with ASGI frameworks such as FastAPI.
To pursue ODMantic, we need to install the extension using the following pip
command:
pip install odmantic
Creating the database connection
Setting up the database connectivity in ODMantic is the same as what we do with the Beanie mapper, except that the setup includes creating an engine that will handle all its CRUD operations. This engine is AIOEngine
from the odmantic
module, which requires both the motor client object and the database name to be created successfully. The following is a complete implementation of the...