AttributeError: Depends object has no attribute query in FastAPI
Inject dependencies via function parameter defaults (db: Session = Depends(get_db)) rather than calling methods directly on the Depends class.
Root Cause Analysis
This error occurs when Python executes code that treats a FastAPI Depends instance as an active database session or request object (e.g. db = Depends(get_db); db.query(User)), attempting to call .query on the unresolved Depends container object.
1. How FastAPI Dependency Injection Works
In FastAPI, Depends(dependency_func) is a marker class used solely for parameter metadata declaration in route function signatures. FastAPI's dependency resolution system inspects route signatures, executes the dependency function (like get_db()), and injects the actual return value into the route handler at request time.
2. Invoking Depends Directly Outside Route Signatures
Writing db = Depends(get_db) inside a helper function or class body does NOT execute the dependency. It merely returns a fastapi.params.Depends object. Attempting db.query() fails because Depends does not have database querying methods.
3. Mixing Up SQLAlchemy Session and Depends Marker
Beginners frequently confuse the type annotation with the default value assignment, leading to un-injected objects.
4. Modern Annotated Syntax in FastAPI 0.95+
Modern FastAPI recommends Annotated[Session, Depends(get_db)] for cleaner separation of type hints and runtime dependency markers.
Reproduction Code (MCVE)
# Simulating calling .query directly on a Depends marker
class Depends:
def __init__(self, dependency=None):
self.dependency = dependency
db = Depends()
users = db.query
Solution 1: Inject Dependencies via Route Handler Parameter Defaults
Declare the dependency in the route signature where FastAPI automatically injects the resolved database session.
def get_database_session():
# Simulating database session generator
return {'status': 'connected', 'engine': 'postgresql'}
# Proper route handler pattern
def get_users_endpoint(db: dict = None):
db = db or get_database_session()
print(f'Querying database session: {db["engine"]}')
return [{'id': 1, 'username': 'admin'}]
print(get_users_endpoint())
Solution 2: Use Modern typing.Annotated Dependency Declaration
Use Annotated for clean, standard Python type annotations compatible with FastAPI, IDE auto-completion, and linters.
from typing import Annotated
class DBSession:
def query_all(self):
return ['user1', 'user2']
def route_handler(db: DBSession):
return db.query_all()
print(f'Users retrieved: {route_handler(DBSession())}')
A common mistake is calling Depends(get_db()) with parentheses inside the dependency definition. Always pass the callable function reference Depends(get_db) without calling it, so FastAPI can manage the generator lifecycle (yield and teardown). Edge cases occur with class-based dependencies: when using Depends(AuthService), ensure AuthService implements __call__ or has a default __init__. Contrast this error with TypeError: 'Depends' object is not callable, which occurs when trying to invoke a Depends marker as a function.