Bird
Raised Fist0
FastAPIframework~20 mins

Depends function basics 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
🎖️
Depends Mastery
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 endpoint using Depends?

Consider this FastAPI code snippet:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_query():
    return "query_value"

@app.get("/items")
async def read_items(q: str = Depends(get_query)):
    return {"q": q}

What will be the JSON response when calling /items?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_query():
    return "query_value"

@app.get("/items")
async def read_items(q: str = Depends(get_query)):
    return {"q": q}
A{"q": "query_value"}
B{"q": null}
CHTTP 422 Unprocessable Entity error
D{"q": ""}
Attempts:
2 left
💡 Hint

Think about what the Depends function does when used as a default value.

state_output
intermediate
2:00remaining
What is the value of 'user' after this dependency injection?

Given this FastAPI code:

from fastapi import Depends, FastAPI

app = FastAPI()

def get_user():
    return {"name": "Alice"}

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

What will be the output JSON when calling /profile?

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def get_user():
    return {"name": "Alice"}

@app.get("/profile")
async def profile(user: dict = Depends(get_user)):
    return user
A{}
B{"user": "Alice"}
C{"name": "Alice"}
DHTTP 500 Internal Server Error
Attempts:
2 left
💡 Hint

Check what the dependency function returns and how it is used in the endpoint.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in Depends usage?

Identify which code snippet will cause a syntax error when using Depends in FastAPI.

A
async def endpoint(dep Depends(get_dep)):
    return dep
B
async def endpoint(dep: str = Depends(get_dep)):
    return dep
C
async def endpoint(dep=Depends(get_dep)):
    return dep
D
ped nruter    
:))ped_teg(sdnepeD = rts :ped(tniopdne fed cnysa
Attempts:
2 left
💡 Hint

Look carefully at the function parameter syntax.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI endpoint raise a runtime error?

Examine this code:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_number():
    return 42

@app.get("/number")
async def read_number(num: int = Depends(get_number)):
    return {"num": num + 1}

When calling /number, a runtime error occurs. Why?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_number():
    return 42

@app.get("/number")
async def read_number(num: int = Depends(get_number)):
    return {"num": num + 1}
ABecause get_number returns int but FastAPI expects a str for query parameters
BNo runtime error occurs; the output is {"num": 43}
CBecause num is None and cannot be added to 1
DBecause Depends does not support functions returning int
Attempts:
2 left
💡 Hint

Consider the type returned by the dependency and how it is used.

🧠 Conceptual
expert
2:00remaining
Which statement best describes how Depends works in FastAPI?

Choose the most accurate description of the Depends function behavior in FastAPI.

ADepends automatically converts all dependency return values to strings before injection.
BDepends caches the dependency function result globally and reuses it for all requests.
CDepends requires the dependency function to be async and returns a coroutine object.
DDepends calls the dependency function once per request and injects its return value into the endpoint parameter.
Attempts:
2 left
💡 Hint

Think about how dependencies are executed and their scope.

Practice

(1/5)
1. What is the main purpose of the Depends function in FastAPI?
easy
A. To create HTML templates
B. To define database models
C. To inject dependencies automatically into path operation functions
D. To handle HTTP status codes

Solution

  1. Step 1: Understand what Depends does

    Depends is used to declare dependencies that FastAPI will automatically provide to your route functions.
  2. Step 2: Identify the main use case

    It helps inject reusable code like authentication, database sessions, or other shared logic into routes.
  3. Final Answer:

    To inject dependencies automatically into path operation functions -> Option C
  4. Quick Check:

    Depends injects dependencies = C [OK]
Hint: Depends injects reusable code into routes automatically [OK]
Common Mistakes:
  • Confusing Depends with database or template functions
  • Thinking Depends handles HTTP status codes
  • Assuming Depends creates models
2. Which of the following is the correct way to declare a dependency in a FastAPI route using Depends?
easy
A. def read_items(db=Depends(get_db)): pass
B. def read_items(db: Depends(get_db)): pass
C. def read_items(db: Depends = get_db): pass
D. def read_items(db=Depends): pass

Solution

  1. Step 1: Recall Depends syntax

    The correct syntax is to assign the parameter a default value of Depends with the dependency function inside.
  2. Step 2: Match the correct option

    def read_items(db=Depends(get_db)): pass uses db=Depends(get_db), which is the proper way to declare a dependency.
  3. Final Answer:

    def read_items(db=Depends(get_db)): pass -> Option A
  4. Quick Check:

    Depends usage = parameter=Depends(function) [OK]
Hint: Use parameter=Depends(function) to declare dependencies [OK]
Common Mistakes:
  • Using type annotation instead of default value for Depends
  • Passing Depends without parentheses
  • Assigning Depends without a function
3. Given the code below, what will be the output when accessing the /items/ endpoint?
from fastapi import FastAPI, Depends

app = FastAPI()

def get_number():
    return 42

@app.get('/items/')
def read_items(number: int = Depends(get_number)):
    return {"number": number}
medium
A. {"number": "get_number"}
B. {"number": 42}
C. Error: missing required parameter
D. {"number": null}

Solution

  1. Step 1: Understand dependency injection

    The get_number function returns 42, and FastAPI injects this value into the number parameter.
  2. Step 2: Check the returned response

    The route returns a dictionary with key "number" and value 42, so the output is {"number": 42}.
  3. Final Answer:

    {"number": 42} -> Option B
  4. Quick Check:

    Depends injects 42 = {"number": 42} [OK]
Hint: Depends calls function and injects return value [OK]
Common Mistakes:
  • Expecting the function name instead of its return value
  • Thinking parameter is missing if not passed explicitly
  • Assuming null is returned if no argument given
4. What is wrong with the following FastAPI code using Depends? How to fix it?
from fastapi import FastAPI, Depends

app = FastAPI()

def get_user():
    return "Alice"

@app.get('/user/')
def read_user(user: str = Depends):
    return {"user": user}
medium
A. Depends is missing the dependency function; fix by using Depends(get_user)
B. The route path is invalid; fix by changing '/user/' to '/users/'
C. The return type is wrong; fix by returning a list instead of dict
D. The function get_user should accept parameters; fix by adding parameters

Solution

  1. Step 1: Identify the Depends usage error

    The parameter uses Depends without specifying the dependency function, which is incorrect.
  2. Step 2: Correct the Depends syntax

    It should be Depends(get_user) to tell FastAPI which function to call for the dependency.
  3. Final Answer:

    Depends is missing the dependency function; fix by using Depends(get_user) -> Option A
  4. Quick Check:

    Depends needs function argument = Depends(get_user) [OK]
Hint: Always pass the dependency function inside Depends() [OK]
Common Mistakes:
  • Using Depends without parentheses or function
  • Changing route path unnecessarily
  • Changing return type without reason
5. How can you use Depends to share a database session across multiple routes without repeating code? Choose the best approach.
hard
A. Use Depends without any function to automatically get the session
B. Pass the session as a global variable to all routes
C. Manually create a session inside each route function
D. Create a function that returns the session and use Depends on it in each route

Solution

  1. Step 1: Understand code reuse with Depends

    Depends allows you to write a function that creates or yields a database session once and injects it wherever needed.
  2. Step 2: Identify the best practice

    Creating a session function and using Depends on it in routes avoids repetition and manages session lifecycle cleanly.
  3. Final Answer:

    Create a function that returns the session and use Depends on it in each route -> Option D
  4. Quick Check:

    Use Depends with session function for reuse = D [OK]
Hint: Use Depends with a session function to share DB session [OK]
Common Mistakes:
  • Using global variables for sessions (not safe)
  • Creating sessions manually in every route (repetitive)
  • Using Depends without specifying a function