Bird
Raised Fist0
FastAPIframework~10 mins

Dependencies with parameters 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 dependency function with a parameter.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def common_parameters(q: str = [1]):
    return {"q": q}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons
Drag options to blanks, or click blank then click option'
A"default"
BFalse
CNone
DTrue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string like "default" instead of None for optional parameters.
Forgetting to set a default value, making the parameter required.
2fill in blank
medium

Complete the code to inject a dependency with a parameter into a path operation.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def query_extractor(q: str = None):
    return q

@app.get("/search/")
async def search(q: str = Depends([1])):
    return {"query": q}
Drag options to blanks, or click blank then click option'
Aquery_extractor
BDepends
CFastAPI
Dsearch
Attempts:
3 left
💡 Hint
Common Mistakes
Passing Depends itself instead of the dependency function.
Passing the FastAPI app instance instead of a function.
3fill in blank
hard

Fix the error in the dependency function parameter default value.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def pagination(skip: int = [1]):
    return {"skip": skip}

@app.get("/items/")
async def list_items(pagination: dict = Depends(pagination)):
    return pagination
Drag options to blanks, or click blank then click option'
A"0"
BNone
CFalse
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string "0" instead of integer 0 as default.
Using None for a parameter that expects an int without Optional.
4fill in blank
hard

Fill both blanks to create a dependency with two parameters and use it in a path operation.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def pagination(skip: int = 0, limit: int = [1]):
    return {"skip": skip, "limit": limit}

@app.get("/items/")
async def list_items(pagination: dict = Depends([2])):
    return pagination
Drag options to blanks, or click blank then click option'
A10
Bpagination
C5
Dlist_items
Attempts:
3 left
💡 Hint
Common Mistakes
Using the path operation function name instead of the dependency function.
Setting limit default to a string instead of an integer.
5fill in blank
hard

Fill all three blanks to create a dependency with parameters and use it with type hints in the path operation.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def query_params(q: str = None, skip: int = 0, limit: int = [1]):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/search/")
async def search_items(params: dict = Depends([2])) -> [3]:
    return params
Drag options to blanks, or click blank then click option'
A20
Bquery_params
Cdict
Dlist
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect default values for limit.
Passing the wrong function to Depends.
Using wrong or missing return type hints.

Practice

(1/5)
1. What is the main purpose of using dependencies with parameters in FastAPI?
easy
A. To automatically generate HTML templates
B. To create global variables accessible everywhere
C. To replace route functions with classes
D. To customize shared code by passing arguments to dependencies

Solution

  1. Step 1: Understand dependency role

    Dependencies in FastAPI are reusable pieces of code that can be shared across routes.
  2. Step 2: Recognize parameter use

    Adding parameters to dependencies allows customizing their behavior for different routes or situations.
  3. Final Answer:

    To customize shared code by passing arguments to dependencies -> Option D
  4. Quick Check:

    Dependencies with parameters = customize shared code [OK]
Hint: Dependencies with parameters customize shared logic easily [OK]
Common Mistakes:
  • Thinking dependencies create global variables
  • Confusing dependencies with route handlers
  • Assuming dependencies generate HTML
2. Which of the following is the correct way to pass a parameter to a dependency in FastAPI?
easy
A. Depends(get_user(user_id=5))
B. Depends(get_user, user_id=5)
C. Depends(get_user)(user_id=5)
D. Depends(get_user)[user_id=5]

Solution

  1. Step 1: Recall Depends usage

    Depends expects a callable or a call to a callable that returns a dependency.
  2. Step 2: Passing parameters

    To pass parameters, you call the dependency function inside Depends, like Depends(get_user(user_id=5)).
  3. Final Answer:

    Depends(get_user(user_id=5)) -> Option A
  4. Quick Check:

    Call dependency inside Depends to pass parameters [OK]
Hint: Call dependency inside Depends() to pass parameters [OK]
Common Mistakes:
  • Passing parameters directly to Depends without calling
  • Using brackets [] instead of parentheses ()
  • Trying to call Depends as a function with parameters
3. Given this code snippet, what will be the output when accessing the endpoint?
from fastapi import FastAPI, Depends

app = FastAPI()

def get_multiplier(factor: int):
    def multiplier(value: int):
        return value * factor
    return multiplier

@app.get("/multiply")
async def multiply(value: int, multiply_func = Depends(get_multiplier(3))):
    return {"result": multiply_func(value)}
medium
A. Error because Depends cannot take parameters
B. {"result": 6} when value=3
C. {"result": 9} when value=3
D. {"result": 3} when value=3

Solution

  1. Step 1: Understand get_multiplier

    get_multiplier(3) returns a function that multiplies input by 3.
  2. Step 2: Analyze endpoint call

    When calling /multiply with value=3, multiply_func(3) returns 3 * 3 = 9.
  3. Final Answer:

    {"result": 9} when value=3 -> Option C
  4. Quick Check:

    Dependency returns multiplier with factor 3, output 9 [OK]
Hint: Multiply value by factor passed in dependency [OK]
Common Mistakes:
  • Assuming Depends cannot take parameters
  • Confusing returned function with direct value
  • Mixing up multiplication factor
4. Identify the error in this FastAPI dependency usage:
def get_limit(limit: int = 10):
    return limit

@app.get("/items")
async def read_items(limit = Depends(get_limit(limit=20))):
    return {"limit": limit}
medium
A. Default value in get_limit conflicts with parameter passed
B. Cannot pass parameters directly inside Depends like get_limit(limit=20)
C. Missing type annotation for limit in read_items
D. Depends should be imported from fastapi.dependencies

Solution

  1. Step 1: Check Depends usage

    Depends expects a callable or a call to a callable without parameters directly inside Depends.
  2. Step 2: Correct way to pass parameters

    To pass parameters, wrap get_limit in another function or use a lambda to supply parameters.
  3. Final Answer:

    Cannot pass parameters directly inside Depends like get_limit(limit=20) -> Option B
  4. Quick Check:

    Depends() must wrap callable, not call with parameters directly [OK]
Hint: Wrap parameterized dependency call outside Depends() [OK]
Common Mistakes:
  • Calling dependency with parameters inside Depends directly
  • Ignoring need for wrapper function
  • Wrong import path for Depends
5. How can you create a reusable dependency with a parameter that changes per route in FastAPI? Choose the best approach.
def common_dep(param: str):
    def dependency():
        return f"Value is {param}"
    return dependency

@app.get("/route1")
async def route1(dep = Depends(common_dep("A"))):
    return {"msg": dep}

@app.get("/route2")
async def route2(dep = Depends(common_dep("B"))):
    return {"msg": dep}
hard
A. Define a function returning a dependency function with parameter, then call it inside Depends
B. Use global variables to store param values for each route
C. Pass parameters directly to Depends without wrapping
D. Create separate dependency functions for each parameter value

Solution

  1. Step 1: Understand reusable dependency pattern

    Define a function that returns a dependency function customized by parameters.
  2. Step 2: Apply pattern per route

    Call this function with different parameters inside Depends for each route to customize behavior.
  3. Final Answer:

    Define a function returning a dependency function with parameter, then call it inside Depends -> Option A
  4. Quick Check:

    Wrap dependency with parameter function, call inside Depends [OK]
Hint: Wrap parameterized dependency in function, call inside Depends [OK]
Common Mistakes:
  • Using global variables instead of parameters
  • Passing parameters directly to Depends without wrapping
  • Duplicating dependency functions unnecessarily