0
0
FastAPIframework~20 mins

Sub-dependencies in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
FastAPI Sub-dependencies Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this FastAPI sub-dependency example?
Consider the following FastAPI code with sub-dependencies. What will be the JSON response when a GET request is made to /items/42?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_user():
    return {"user_id": 1, "name": "Alice"}

def get_item(user: dict = Depends(get_user), item_id: int = 0):
    return {"item_id": item_id, "owner": user["name"]}

@app.get("/items/{item_id}")
async def read_item(item: dict = Depends(get_item)):
    return item
A{"item_id": 0, "owner": "Alice"}
B{"item_id": 42, "owner": 1}
C{"item_id": 42, "owner": "Alice"}
DKeyError at runtime
Attempts:
2 left
💡 Hint
Think about how the path parameter item_id is passed through dependencies.
lifecycle
intermediate
2:00remaining
How many times is the sub-dependency called?
Given this FastAPI code, how many times will get_db be called when a GET request is made to /users/5?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

call_count = {"db": 0}

def get_db():
    call_count["db"] += 1
    return "db_connection"

def get_user(db=Depends(get_db), user_id: int = 0):
    return {"user_id": user_id, "db": db}

@app.get("/users/{user_id}")
async def read_user(user=Depends(get_user)):
    return user
A1
B2
C0
DRaises an error
Attempts:
2 left
💡 Hint
Consider how FastAPI resolves dependencies and sub-dependencies per request.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI sub-dependency raise a validation error?
Examine this code snippet. When calling /orders/10, a validation error occurs. What causes it?
FastAPI
from fastapi import FastAPI, Depends
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str

def get_user():
    return {"id": 1, "name": "Bob"}

def get_order(user: User = Depends(get_user), order_id: int = 0):
    return {"order_id": order_id, "user_name": user.name}

@app.get("/orders/{order_id}")
async def read_order(order=Depends(get_order)):
    return order
ANo error, returns order with user_name 'Bob'
BKeyError because user.name does not exist
CTypeError because order_id is missing
DValidationError because get_user returns dict, not User instance
Attempts:
2 left
💡 Hint
Check the type expected by the user parameter in get_order.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a sub-dependency with parameters?
You want to create a sub-dependency get_token that depends on get_header and also accepts a parameter required: bool. Which option is correct?
A
def get_header():
    return "token123"

def get_token(required: bool = True, header=Depends(get_header)):
    if required and not header:
        raise Exception("Missing token")
    return header
B
def get_header():
    return "token123"

def get_token(header=Depends(get_header), required: bool = True):
    if required and not header:
        raise Exception("Missing token")
    return header
C
def get_header():
    return "token123"

def get_token(required: bool, header=Depends(get_header)):
    if required and not header:
        raise Exception("Missing token")
    return header
D
def get_header():
    return "token123"

def get_token(header=Depends(get_header), required: bool):
    if required and not header:
        raise Exception("Missing token")
    return header
Attempts:
2 left
💡 Hint
In Python, parameters with default values must come after those without defaults.
state_output
expert
3:00remaining
What is the final value of counter['calls'] after two requests?
Given this FastAPI app with sub-dependencies and a mutable state counter, what is the value of counter['calls'] after two separate GET requests to /process/1 and /process/2?
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

counter = {"calls": 0}

def increment_counter():
    counter["calls"] += 1
    return counter["calls"]

def process_item(call_count=Depends(increment_counter), item_id: int = 0):
    return {"item_id": item_id, "call_count": call_count}

@app.get("/process/{item_id}")
async def process_route(result=Depends(process_item)):
    return result
A0
B2
C1
DRaises an error
Attempts:
2 left
💡 Hint
Consider that the counter dictionary is global and mutable.