Bird
0
0

What is the error in the following FastAPI code using sub-dependencies?

medium📝 Debug Q14 of 15
FastAPI - Dependency Injection
What is the error in the following FastAPI code using sub-dependencies?
from fastapi import FastAPI, Depends

app = FastAPI()

def sub_dep():
    return "data"

def main_dep(data: str = Depends(sub_dep)):
    return data

@app.get("/test")
async def test_endpoint(info: str = Depends(main_dep())):
    return {"info": info}
ACalling main_dep() inside Depends instead of passing the function
BMissing return statement in sub_dep
CIncorrect route path syntax
DUsing async def for endpoint without await
Step-by-Step Solution
Solution:
  1. Step 1: Identify how Depends should be used

    Depends expects a function reference, not a function call. Calling main_dep() executes it immediately, which is wrong.
  2. Step 2: Check the code for this mistake

    The code uses Depends(main_dep()), which calls the function instead of passing it. It should be Depends(main_dep).
  3. Final Answer:

    Calling main_dep() inside Depends instead of passing the function -> Option A
  4. Quick Check:

    Depends needs function, not function call [OK]
Quick Trick: Pass function to Depends, don't call it [OK]
Common Mistakes:
MISTAKES
  • Calling dependency functions inside Depends()
  • Confusing async usage with dependency errors
  • Ignoring Depends syntax rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes