python type_error ai_generated true

fastapi.exceptions.FastAPIError: Invalid dependency: 'get_db' is not a callable or a class.

ID: python/fastapi-dependency-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-04-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Dependencies in FastAPI must be callables (functions or classes) that return the required value.

generic

中文

FastAPI 中的依赖项必须是可调用对象(函数或类),返回所需的值。

Workarounds

  1. 100% success Define a proper dependency function
    def get_db():
        return db_session
    
    @app.get('/items')
    def read_items(db=Depends(get_db)):
        ...
  2. 90% success Use a class as a dependency with __call__
    class DBSession:
        def __call__(self):
            return db_session
    
    app.dependency_overrides[get_db] = DBSession()

Dead Ends

Common approaches that don't work:

  1. Passing a string or integer as a dependency 100% fail

    Must be a callable.

  2. Using a class without __call__ 80% fail

    Classes must be instantiable or have __call__.