pythonmongodbdependency-injectionfastapibeanie

How to use Mongo model in FastAPI Depends?


When I trying to run my endpoint, I getting CollectionWasNotInitialized error in Depends function. If I move code from dependency to endpoint body, it works. init_beanie initializing at server start in lifespan. Is it real to use mongo model in Depends? Or may be it's not good practice?

Initialization in main.py:

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_beanie(
        database=db,
        document_models=[
            User, Purchase, Company
        ],
    )
    yield

Dependency function:

async def my_dependency_function(company_id: str):
    company_id = ObjectId(company_id)
    company = await Company.find_one({"_id": company_id})
    return {"company_bm": company.bm}

My Model:

class Company(Document):
    bm: str

    class Settings:
        name = "companies"

My endpoint:

@rt.get("/items/{company_id}")
async def read_item(
    company_id: str,
    my_dependency: dict = Depends(my_dependency_function)
):
    return my_dependency

Solution

  • You can use another dependency to get a connection to the database:

    client = AsyncIOMotorClient(DATABASE_URL, uuidRepresentation="standard")
    db = client["DB_NAME"]
    
    
    def get_mongo_client():
        return db
    
    async def my_dependency_function(
        company_id: str,
        db: AsyncIOMotorClient = Depends(get_mongo_client)
    ):
        company_id = ObjectId(company_id)
        company_collection = db["companies"]
        company = await company_collection.find_one({"_id": company_id})
        return {"company_bm": company["bm"]}