Install required packages#

# Install SQLAlchemy: for ORM
pip install SQLAlchemy
# Optional asyncio
pip install "sqlalchemy[asyncio]"


# Install asyncpg: for async operations
pip install asyncpg


# Install Pydantic: for validation
pip install pydantic
# For email validation
pip install "pydantic[email]"



# Install fastAPI
pip install fastapi uvicorn

Follow the code structure#

app/ ├── main.py ├── db.py ├── models.py ├── schemas.py └── crud.py

Run to init model (database)#

python db.py

async def init_models():
    async with engine.begin() as conn:
        # Run the synchronous `create_all` within the async context
        await conn.run_sync(Base.metadata.create_all)

import asyncio


# Run the async function
if __name__ == "__main__":
    asyncio.run(init_models())

References#

https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#asyncio-platform-installation-notes-including-apple-m1