Bird
Raised Fist0
FastAPIframework~20 mins

Shared 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 Shared 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 shared dependency example?

Consider this FastAPI code using a shared dependency:

from fastapi import FastAPI, Depends

app = FastAPI()

async def common_dep():
    return "shared value"

@app.get("/one")
async def one(dep=Depends(common_dep)):
    return {"result": dep}

@app.get("/two")
async def two(dep=Depends(common_dep)):
    return {"result": dep + " appended"}

What will be the JSON response from the endpoint /two?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

async def common_dep():
    return "shared value"

@app.get("/one")
async def one(dep=Depends(common_dep)):
    return {"result": dep}

@app.get("/two")
async def two(dep=Depends(common_dep)):
    return {"result": dep + " appended"}
A{"result": "shared value appended appended"}
B{"result": "shared value"}
C{"result": "shared value appended"}
D{"result": null}
Attempts:
2 left
💡 Hint

Think about what the dependency common_dep returns and how it is used in the /two endpoint.

state_output
intermediate
2:00remaining
How many times is the shared dependency called in this FastAPI example?

Given this FastAPI code:

from fastapi import FastAPI, Depends

app = FastAPI()

call_count = 0

async def shared_dep():
    global call_count
    call_count += 1
    return call_count

@app.get("/first")
async def first(dep=Depends(shared_dep)):
    return {"count": dep}

@app.get("/second")
async def second(dep=Depends(shared_dep)):
    return {"count": dep}

If a client calls /first and then /second in sequence, what will be the value of call_count after both calls?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

call_count = 0

async def shared_dep():
    global call_count
    call_count += 1
    return call_count

@app.get("/first")
async def first(dep=Depends(shared_dep)):
    return {"count": dep}

@app.get("/second")
async def second(dep=Depends(shared_dep)):
    return {"count": dep}
A0
B2
C3
D1
Attempts:
2 left
💡 Hint

Each endpoint call triggers the dependency function once.

🔧 Debug
advanced
2:00remaining
What error does this FastAPI shared dependency code raise?

Examine this FastAPI code snippet:

from fastapi import FastAPI, Depends

app = FastAPI()

async def dep():
    return 42

@app.get("/error")
async def error(dep=Depends(dep())):
    return {"value": dep}

What error will occur when starting or calling the /error endpoint?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

async def dep():
    return 42

@app.get("/error")
async def error(dep=Depends(dep())):
    return {"value": dep}
ATypeError: 'int' object is not callable
BNo error, returns {"value": 42}
CSyntaxError: invalid syntax
DRuntimeError: Dependency function called at import time
Attempts:
2 left
💡 Hint

Check how the dependency is passed to Depends.

🧠 Conceptual
advanced
2:00remaining
Which option correctly shares a database session dependency in FastAPI?

You want to share a database session dependency across multiple endpoints in FastAPI. Which code snippet correctly implements this shared dependency?

A
def get_db():
    db = Session()
    try:
        yield db
    finally:
        db.close()

@app.get("/items")
async def read_items(db=Depends(get_db)):
    return db.query(Item).all()
B
def get_db():
    db = Session()
    return db
    db.close()

@app.get("/items")
async def read_items(db=Depends(get_db)):
    return db.query(Item).all()
C
def get_db():
    db = Session()
    yield db
    db.close()

@app.get("/items")
async def read_items(db=Depends(get_db())):
    return db.query(Item).all()
D
def get_db():
    db = Session()
    yield db

@app.get("/items")
async def read_items(db=Depends(get_db)):
    return db.query(Item).all()
Attempts:
2 left
💡 Hint

Think about how to properly open and close resources with dependencies.

📝 Syntax
expert
2:00remaining
What is the correct syntax to declare a shared dependency with parameters in FastAPI?

Given a dependency function that accepts parameters, which option correctly declares it for use as a shared dependency in FastAPI?

def common_dep(param: int):
    return param * 2
FastAPI
def common_dep(param: int):
    return param * 2
A
@app.get("/calc")
async def calc(value: int, result=Depends(lambda: common_dep(value))):
    return {"result": result}
B
@app.get("/calc")
async def calc(value: int, result=Depends(common_dep)):
    return {"result": result}
C
@app.get("/calc")
async def calc(value: int, result=Depends(common_dep(value))):
    return {"result": result}
D
}tluser :"tluser"{ nruter    
:))ped_nommoc(sdnepeD=tluser ,tni :eulav(clac fed cnysa
)"clac/"(teg.ppa@
Attempts:
2 left
💡 Hint

Consider how to pass parameters to dependencies dynamically.

Practice

(1/5)
1. What is the main purpose of using Depends() in FastAPI for shared dependencies?
easy
A. To reuse code across multiple routes by declaring common dependencies
B. To create a new route in the application
C. To handle database connections manually
D. To define the response model for an endpoint

Solution

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

    Depends() is used in FastAPI to declare dependencies that can be shared across multiple routes.

  2. Step 2: Identify the main benefit

    Using shared dependencies helps reuse code and keep the app clean and maintainable.

  3. Final Answer:

    To reuse code across multiple routes by declaring common dependencies -> Option A
  4. Quick Check:

    Shared dependencies = reuse code [OK]
Hint: Depends() means shared code for many routes [OK]
Common Mistakes:
  • Thinking Depends() creates routes
  • Confusing Depends() with response models
  • Assuming Depends() manages database connections directly
2. Which of the following is the correct way to declare a shared dependency in a FastAPI route?
easy
A. def get_db(): return Session(); @app.get('/items') def read_items(db=Depends(get_db)): pass
B. def get_db(): return Session(); @app.get('/items') def read_items(db=get_db()): pass
C. def get_db(): return Session(); @app.get('/items') def read_items(db: Session): pass
D. def get_db(): return Session(); @app.get('/items') def read_items(db=Depends()): pass

Solution

  1. Step 1: Review correct dependency syntax

    In FastAPI, dependencies are declared using Depends(function_name) inside the function parameters.
  2. Step 2: Check each option

    def get_db(): return Session(); @app.get('/items') def read_items(db=Depends(get_db)): pass correctly uses db=Depends(get_db). def get_db(): return Session(); @app.get('/items') def read_items(db=get_db()): pass calls the function directly, which is incorrect. def get_db(): return Session(); @app.get('/items') def read_items(db: Session): pass lacks Depends, so no injection happens. def get_db(): return Session(); @app.get('/items') def read_items(db=Depends()): pass uses Depends without a function, which is invalid.
  3. Final Answer:

    def get_db(): return Session(); @app.get('/items') def read_items(db=Depends(get_db)): pass -> Option A
  4. Quick Check:

    Depends() needs function inside [OK]
Hint: Depends() must wrap the dependency function [OK]
Common Mistakes:
  • Calling dependency function directly in parameter
  • Forgetting to use Depends() wrapper
  • Using Depends() without specifying the function
3. Given the code below, what will be the output when accessing /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def common_dep():
    return "shared value"

@app.get('/items/{item_id}')
def read_item(item_id: int, value: str = Depends(common_dep)):
    return {"item_id": item_id, "value": value}
medium
A. Error: Missing required parameter 'value'
B. {"item_id": 42, "value": 42}
C. {"item_id": 42, "value": null}
D. {"item_id": 42, "value": "shared value"}

Solution

  1. Step 1: Understand dependency injection

    The function common_dep returns the string "shared value". FastAPI injects this into the value parameter via Depends(common_dep).
  2. Step 2: Check the returned JSON

    The route returns a dictionary with item_id from the path and value from the dependency. So the output will be {"item_id": 42, "value": "shared value"}.
  3. Final Answer:

    {"item_id": 42, "value": "shared value"} -> Option D
  4. Quick Check:

    Dependency injects "shared value" [OK]
Hint: Depends injects return value as parameter [OK]
Common Mistakes:
  • Assuming dependency returns item_id
  • Expecting error due to missing parameter
  • Thinking value will be null without explicit call
4. Identify the error in the following FastAPI code using shared dependencies:
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token():
    return "token123"

@app.get('/secure')
def secure_route(token: str = Depends()):
    return {"token": token}
medium
A. The function secure_route should not have parameters
B. The dependency function get_token() should return an int
C. Depends() is missing the dependency function inside
D. The route decorator is missing parentheses

Solution

  1. Step 1: Check Depends usage

    The parameter token uses Depends() without specifying the dependency function. This is incorrect syntax.
  2. Step 2: Correct usage

    Depends must wrap the function providing the dependency, so it should be Depends(get_token).
  3. Final Answer:

    Depends() is missing the dependency function inside -> Option C
  4. Quick Check:

    Depends() needs function argument [OK]
Hint: Depends() always needs a function inside [OK]
Common Mistakes:
  • Using Depends() without argument
  • Expecting Depends() to work without function
  • Confusing Depends() with decorator syntax
5. You want to share a database session dependency across multiple routes but also ensure it closes after each request. Which approach correctly uses shared dependencies with cleanup in FastAPI?
hard
A. Create the session globally once and reuse it without closing
B. Use a dependency function with yield that creates the session, yields it, then closes it after
C. Pass the session as a normal parameter without Depends()
D. Use Depends() but close the session manually inside each route

Solution

  1. Step 1: Understand dependency cleanup

    FastAPI supports dependencies with cleanup by using yield inside the dependency function. This allows setup before yield and cleanup after.
  2. Step 2: Apply to database session

    The correct pattern is to create the session, yield it for use in routes, then close it after the request finishes.
  3. Final Answer:

    Use a dependency function with yield that creates the session, yields it, then closes it after -> Option B
  4. Quick Check:

    Yield in dependency = setup and cleanup [OK]
Hint: Use yield in dependency for setup and cleanup [OK]
Common Mistakes:
  • Reusing global session without closing
  • Closing session inside route instead of dependency
  • Not using Depends() for session injection