python type_error ai_generated true

TypeError: missing 1 required positional argument: 'db'

ID: python/fastapi-depends-missing-parameter

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

A dependency function expects a parameter that is not provided by the caller or the dependency injection system.

generic

中文

依赖函数期望一个参数,但调用方或依赖注入系统未提供。

Workarounds

  1. 95% success Ensure the dependency is properly injected using Depends
    from fastapi import Depends
    async def get_db():
        return db
    @app.get('/items')
    async def read_items(db=Depends(get_db)):
  2. 85% success Define the dependency as a class with __call__
    class DBSession:
        def __call__(self):
            return db
    @app.get('/items')
    async def read_items(db=Depends(DBSession())):

Dead Ends

Common approaches that don't work:

  1. Adding a default value to the parameter 50% fail

    May not solve the underlying issue if the dependency is required.

  2. Removing the dependency from the route 80% fail

    Breaks the functionality that requires the dependency.