Bird
Raised Fist0
FastAPIframework~20 mins

Path operation dependencies in FastAPI - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
FastAPI Dependency 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 path operation with dependencies?

Consider this FastAPI code snippet:

from fastapi import FastAPI, Depends

app = FastAPI()

def common_parameters(q: str | None = None):
    return {"q": q}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

What will be the JSON response when a client requests /items/?q=hello?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def common_parameters(q: str | None = None):
    return {"q": q}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons
A{"q": "hello"}
BHTTP 422 Unprocessable Entity error
C{}
D{"q": null}
Attempts:
2 left
💡 Hint

Think about how query parameters are passed and how the dependency function returns them.

state_output
intermediate
2:00remaining
What is the value of 'user' inside the path operation?

Given this FastAPI code:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_user(token: str):
    if token == "secret":
        return "admin"
    return "guest"

@app.get("/profile")
async def profile(user: str = Depends(get_user)):
    return {"user": user}

What will be the response when a client calls /profile?token=secret?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_user(token: str):
    if token == "secret":
        return "admin"
    return "guest"

@app.get("/profile")
async def profile(user: str = Depends(get_user)):
    return {"user": user}
A{"user": "guest"}
B{"user": "admin"}
CHTTP 422 Unprocessable Entity error
D{"user": null}
Attempts:
2 left
💡 Hint

Check how the token query parameter is passed to the dependency.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in FastAPI dependency declaration?

Which of the following FastAPI dependency declarations will cause a syntax error?

Adef dep(q: str = Depends()): return q
Bq nruter :))(sdnepeD = rts :q(ped fed
Cq nruter :)sdnepeD = rts :q(ped fed
Ddef dep(q: str = Depends): return q
Attempts:
2 left
💡 Hint

Check how Depends is used as a callable.

lifecycle
advanced
2:00remaining
How many times is the dependency function called per request?

Given this FastAPI code:

from fastapi import FastAPI, Depends

app = FastAPI()

call_count = 0

def dep():
    global call_count
    call_count += 1
    return call_count

@app.get("/count")
async def count_calls(a: int = Depends(dep), b: int = Depends(dep)):
    return {"a": a, "b": b}

How many times is dep called when a client requests /count?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

call_count = 0

def dep():
    global call_count
    call_count += 1
    return call_count

@app.get("/count")
async def count_calls(a: int = Depends(dep), b: int = Depends(dep)):
    return {"a": a, "b": b}
A2
B1
C0
DDepends on caching settings
Attempts:
2 left
💡 Hint

Each Depends call creates a separate dependency instance.

🔧 Debug
expert
2:00remaining
Why does this FastAPI dependency cause a runtime error?

Examine this FastAPI code snippet:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_token(token: str):
    return token

@app.get("/secure")
async def secure_route(token: str = Depends(get_token)):
    return {"token": token}

When calling /secure without query parameters, what error occurs and why?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token(token: str):
    return token

@app.get("/secure")
async def secure_route(token: str = Depends(get_token)):
    return {"token": token}
AReturns {"token": null}
BHTTP 500 Internal Server Error due to missing dependency
CHTTP 422 Unprocessable Entity because 'token' is missing
DReturns {"token": ""} (empty string)
Attempts:
2 left
💡 Hint

Consider how FastAPI handles required query parameters in dependencies.

Practice

(1/5)
1. What is the main purpose of using Depends() in FastAPI path operations?
easy
A. To create a new database connection manually
B. To define the HTTP method for the route
C. To specify the response status code
D. To run shared code before handling requests

Solution

  1. Step 1: Understand the role of Depends()

    Depends() is used to declare dependencies that run shared code before the main path operation function executes.

  2. Step 2: Identify the purpose in FastAPI

    This helps keep code clean by reusing common logic like authentication or database access.

  3. Final Answer:

    To run shared code before handling requests -> Option D
  4. Quick Check:

    Depends() runs shared code before requests [OK]
Hint: Depends() runs shared code before request handling [OK]
Common Mistakes:
  • Thinking Depends() sets HTTP methods
  • Confusing Depends() with response status codes
  • Assuming Depends() manually creates DB connections
2. Which of the following is the correct way to declare a dependency in a FastAPI path operation function?
easy
A. def read_item(item_id: int, user=Depends[get_current_user]):
B. def read_item(item_id: int, user=Depends):
C. def read_item(item_id: int, user=Depends(get_current_user)):
D. def read_item(item_id: int, user=get_current_user()):

Solution

  1. Step 1: Recall the syntax for dependencies

    Dependencies are declared by assigning a parameter to Depends() with the dependency function inside.

  2. Step 2: Check each option

    def read_item(item_id: int, user=Depends(get_current_user)): correctly uses user=Depends(get_current_user). Others have syntax errors or call the function directly.

  3. Final Answer:

    def read_item(item_id: int, user=Depends(get_current_user)): -> Option C
  4. Quick Check:

    Depends() with function inside parentheses [OK]
Hint: Use Depends(function_name) with parentheses [OK]
Common Mistakes:
  • Calling the dependency function directly
  • Using Depends without parentheses
  • Using square brackets instead of parentheses
3. Given the code below, what will be the output when accessing /items/5?
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token():
    return "token123"

@app.get("/items/{item_id}")
def read_item(item_id: int, token: str = Depends(get_token)):
    return {"item_id": item_id, "token": token}
medium
A. {"item_id": 5, "token": "token123"}
B. {"item_id": 5, "token": null}
C. RuntimeError due to missing token parameter
D. SyntaxError in dependency declaration

Solution

  1. Step 1: Understand dependency execution

    The get_token function returns "token123" and is injected into token parameter via Depends().

  2. Step 2: Check the returned dictionary

    The path operation returns a dictionary with item_id and token keys, so the output includes the token string.

  3. Final Answer:

    {"item_id": 5, "token": "token123"} -> Option A
  4. Quick Check:

    Dependency injects token value correctly [OK]
Hint: Depends injects return value as parameter [OK]
Common Mistakes:
  • Expecting token to be null without dependency
  • Thinking dependency causes runtime error
  • Confusing syntax with runtime errors
4. Identify the error in the following FastAPI code using dependencies:
from fastapi import FastAPI, Depends

app = FastAPI()

def get_user():
    return "user1"

@app.get("/profile")
def profile(user: str = Depends(get_user)):
    return {"user": user}

@app.get("/dashboard")
def dashboard(user = Depends(get_user)):
    return {"dashboard_user": user}
medium
A. Missing type annotation for 'user' in dashboard function
B. Depends() used incorrectly without parentheses
C. get_user function missing return statement
D. Path operation decorator missing on dashboard function

Solution

  1. Step 1: Compare both path operation functions

    The profile function declares user: str = Depends(get_user) with a type annotation.

  2. Step 2: Identify the issue in dashboard

    The dashboard function uses user = Depends(get_user) but lacks a type annotation, which FastAPI requires for dependencies.

  3. Final Answer:

    Missing type annotation for 'user' in dashboard function -> Option A
  4. Quick Check:

    Dependency parameters need type annotations [OK]
Hint: Always add type annotations for Depends parameters [OK]
Common Mistakes:
  • Omitting type annotations on dependency parameters
  • Forgetting parentheses on Depends()
  • Assuming missing decorator causes error
5. You want to reuse a dependency that extracts a user from a token and also check if the user is active before allowing access to multiple routes. How should you combine these checks using FastAPI dependencies?
hard
A. Create two separate dependency functions and use Depends() on both in the path operation
B. Call the user extraction function inside the active check function and use Depends() only on the active check
C. Use a single dependency function that returns user without any checks
D. Use Depends() only on the user extraction function and check active status inside each path operation

Solution

  1. Step 1: Understand dependency chaining

    You can call one dependency inside another to reuse logic and combine checks.

  2. Step 2: Apply chaining for user extraction and active check

    By calling the user extraction inside the active check dependency, you only need to use Depends() on the active check in routes.

  3. Final Answer:

    Call the user extraction function inside the active check function and use Depends() only on the active check -> Option B
  4. Quick Check:

    Chain dependencies by calling one inside another [OK]
Hint: Chain dependencies by calling one inside another [OK]
Common Mistakes:
  • Using multiple Depends() separately causing repeated calls
  • Not chaining dependencies and duplicating code
  • Checking user active status outside dependencies