CodexBloom - Programming Q&A Platform

FastAPI Dependency Injection scenarios with 'TypeError: 'NoneType' object is not callable' When Using Async Functions

๐Ÿ‘€ Views: 256 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
fastapi asyncio sqlalchemy Python

I'm having trouble with I'm updating my dependencies and I'm working with an scenario with FastAPI where I'm getting a `TypeError: 'NoneType' object is not callable` behavior when trying to use dependency injection with async functions... Hereโ€™s my setup: I have a simple FastAPI application where I'm trying to inject a database session into my route handler. I'm using SQLAlchemy for the ORM and asyncpg as the database driver. Below is the relevant code snippet: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, sessionmaker from sqlalchemy.orm import declarative_base DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname" engine = create_async_engine(DATABASE_URL, echo=True) Base = declarative_base() SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False) app = FastAPI() def get_db(): async with SessionLocal() as session: yield session @app.get("/items/{item_id}") async def read_item(item_id: int, db: AsyncSession = Depends(get_db)): # Fetch the item from the database pass ``` When I run the application and try to access the endpoint `/items/1`, I get the mentioned behavior. I suspect it might be related to how the `get_db` dependency is being defined or called, especially with the async context manager. I have checked my FastAPI version which is 0.75.0 and SQLAlchemy version 1.4.27, and I have confirmed that the database connection string is correct. I tried adding some debug statements inside `get_db` to ensure it is being called, and it seems like it doesnโ€™t get executed at all. Additionally, I have tried reloading the application and clearing any cached data, but the scenario continues. Could someone guide to understand what might be going wrong and how to properly set up the dependency injection with async functions in FastAPI? I'm coming from a different tech stack and learning Python. This is for a mobile app running on Ubuntu 22.04. What's the correct way to implement this?