Bird
Raised Fist0
FastAPIframework~10 mins

Sub-dependencies in FastAPI - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a simple dependency function in FastAPI.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def common_parameters():
    return {"q": "fastapi"}

@app.get("/items/")
async def read_items(params: dict = Depends([1])):
    return params
Drag options to blanks, or click blank then click option'
Acommon_parameters
BDepends
CFastAPI
Dread_items
Attempts:
3 left
💡 Hint
Common Mistakes
Passing Depends instead of the function name.
Passing the FastAPI app instance.
Using the endpoint function name as dependency.
2fill in blank
medium

Complete the code to declare a sub-dependency function that depends on another dependency.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def common_parameters():
    return {"q": "fastapi"}

def query_extractor(params: dict = Depends([1])):
    return params.get("q")

@app.get("/search/")
async def search(q: str = Depends(query_extractor)):
    return {"query": q}
Drag options to blanks, or click blank then click option'
AFastAPI
Bcommon_parameters
Csearch
Dquery_extractor
Attempts:
3 left
💡 Hint
Common Mistakes
Using the sub-dependency function itself inside Depends().
Passing the endpoint function name as dependency.
Passing the FastAPI app instance.
3fill in blank
hard

Fix the error in the sub-dependency declaration by completing the blank.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def common_parameters():
    return {"q": "fastapi"}

def query_extractor(params: dict = Depends([1])):
    return params.get("q")

@app.get("/items/")
async def read_items(q: str = Depends(query_extractor)):
    return {"query": q}
Drag options to blanks, or click blank then click option'
Aread_items
Bquery_extractor
Ccommon_parameters
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Referencing the sub-dependency itself inside Depends().
Using the endpoint function name inside Depends().
4fill in blank
hard

Fill both blanks to create a sub-dependency that extracts a header and then use it in the endpoint.

FastAPI
from fastapi import Depends, FastAPI, Header

app = FastAPI()

def user_agent_header(user_agent: str = [1]):
    return user_agent

@app.get("/headers/")
async def read_headers(user_agent: str = Depends([2])):
    return {"User-Agent": user_agent}
Drag options to blanks, or click blank then click option'
AHeader("User-Agent")
Buser_agent_header
CDepends(user_agent_header)
DHeader
Attempts:
3 left
💡 Hint
Common Mistakes
Using Depends() inside the sub-dependency parameter default.
Passing Depends(user_agent_header) instead of the function name in the endpoint.
5fill in blank
hard

Fill all three blanks to create nested dependencies where the endpoint depends on a sub-dependency that depends on another dependency.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def common_parameters():
    return {"token": "abc123"}

def verify_token(params: dict = Depends([1])):
    token = params.get([2])
    if token != "abc123":
        raise Exception("Invalid token")
    return token

@app.get("/secure-data/")
async def secure_data(token: str = Depends([3])):
    return {"token": token}
Drag options to blanks, or click blank then click option'
Acommon_parameters
B"token"
Cverify_token
Dsecure_data
Attempts:
3 left
💡 Hint
Common Mistakes
Using the endpoint function name inside Depends().
Using the wrong key string for the token.
Referencing the sub-dependency inside itself.

Practice

(1/5)
1. What is the main purpose of sub-dependencies in FastAPI?
easy
A. To handle HTTP requests directly
B. To create database connections only
C. To reuse small parts of code inside other dependencies
D. To replace middleware functions

Solution

  1. Step 1: Understand what sub-dependencies do

    Sub-dependencies allow you to reuse small parts of code inside other dependencies, making your code cleaner.
  2. Step 2: Compare options with this purpose

    Only To reuse small parts of code inside other dependencies correctly describes this purpose; others describe unrelated tasks.
  3. Final Answer:

    To reuse small parts of code inside other dependencies -> Option C
  4. Quick Check:

    Sub-dependencies = Reuse code [OK]
Hint: Sub-dependencies help reuse code inside dependencies [OK]
Common Mistakes:
  • Thinking sub-dependencies handle HTTP requests directly
  • Confusing sub-dependencies with middleware
  • Assuming sub-dependencies only manage database connections
2. Which of the following is the correct way to declare a sub-dependency in FastAPI?
easy
A. def sub_dep(): return 'data' def main_dep(sub: str = Depends(sub_dep)): return sub
B. def sub_dep(): return 'data' def main_dep(sub: str = sub_dep()): return sub
C. def sub_dep(): return 'data' def main_dep(sub: str = Depends(sub_dep())): return sub
D. def sub_dep(): return 'data' def main_dep(sub: str): return sub

Solution

  1. Step 1: Recall FastAPI dependency syntax

    Dependencies must be passed as functions inside Depends(), not called directly.
  2. Step 2: Analyze each option

    def sub_dep(): return 'data' def main_dep(sub: str = Depends(sub_dep)): return sub correctly uses Depends(sub_dep) without calling it. Options B and C call the function, which is incorrect. def sub_dep(): return 'data' def main_dep(sub: str): return sub lacks Depends entirely.
  3. Final Answer:

    def sub_dep(): return 'data'\n\ndef main_dep(sub: str = Depends(sub_dep)): return sub -> Option A
  4. Quick Check:

    Use Depends(function) without parentheses [OK]
Hint: Use Depends with function name, no parentheses [OK]
Common Mistakes:
  • Calling the dependency function inside Depends()
  • Not using Depends at all
  • Passing the function call result instead of the function
3. Given the code below, what will be the output when calling /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def sub_dep():
    return "sub-data"

def main_dep(data: str = Depends(sub_dep)):
    return f"main uses {data}"

@app.get("/items/{item_id}")
async def read_item(item_id: int, info: str = Depends(main_dep)):
    return {"item_id": item_id, "info": info}
medium
A. {"item_id": 42, "info": "main_dep"}
B. {"item_id": 42, "info": "main uses sub-data"}
C. {"item_id": 42, "info": "sub-data"}
D. Runtime error due to missing parameters

Solution

  1. Step 1: Understand dependency chaining

    The read_item endpoint depends on main_dep, which depends on sub_dep. The value from sub_dep is passed to main_dep.
  2. Step 2: Trace returned values

    sub_dep() returns "sub-data". main_dep returns "main uses sub-data". So info in read_item is "main uses sub-data".
  3. Final Answer:

    {"item_id": 42, "info": "main uses sub-data"} -> Option B
  4. Quick Check:

    Sub-dependencies chain output correctly [OK]
Hint: Follow dependency chain outputs step-by-step [OK]
Common Mistakes:
  • Ignoring sub-dependency output in main dependency
  • Assuming direct sub_dep output is returned
  • Expecting runtime errors without cause
4. 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}
medium
A. Calling main_dep() inside Depends instead of passing the function
B. Missing return statement in sub_dep
C. Incorrect route path syntax
D. Using async def for endpoint without await

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]
Hint: Pass function to Depends, don't call it [OK]
Common Mistakes:
  • Calling dependency functions inside Depends()
  • Confusing async usage with dependency errors
  • Ignoring Depends syntax rules
5. You want to create a FastAPI endpoint that depends on a main dependency which itself depends on two sub-dependencies. How should you structure the dependencies to ensure both sub-dependencies are called and their results used in the main dependency?
hard
A. Call both sub-dependencies inside main dependency without Depends()
B. Pass sub-dependencies as global variables to main dependency
C. Use a single sub-dependency that returns a tuple of both results
D. Define two sub-dependency functions, then in main dependency use Depends() for both as parameters

Solution

  1. Step 1: Understand sub-dependency usage in main dependency

    FastAPI allows multiple dependencies by declaring parameters with Depends(). To use two sub-dependencies, declare both as parameters with Depends().
  2. Step 2: Evaluate options for correctness

    Define two sub-dependency functions, then in main dependency use Depends() for both as parameters correctly describes this pattern. Call both sub-dependencies inside main dependency without Depends() misses Depends(), so sub-dependencies won't be injected. Use a single sub-dependency that returns a tuple of both results is possible but less clear and not standard. Pass sub-dependencies as global variables to main dependency is incorrect as global variables don't work for dependency injection.
  3. Final Answer:

    Define two sub-dependency functions, then in main dependency use Depends() for both as parameters -> Option D
  4. Quick Check:

    Multiple Depends parameters call multiple sub-dependencies [OK]
Hint: Use multiple Depends() parameters in main dependency [OK]
Common Mistakes:
  • Calling sub-dependencies directly without Depends
  • Trying to pass sub-dependencies as globals
  • Combining sub-dependencies into one without clear structure