Bird
Raised Fist0
FastAPIframework~20 mins

Global 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 Global 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 app with global dependencies?

Consider this FastAPI app where a global dependency adds a header. What will the response headers contain when you call /items/42?

FastAPI
from fastapi import FastAPI, Depends, Header

app = FastAPI()

def common_header(x_token: str = Header(...)):
    return x_token

@app.get("/items/{item_id}", dependencies=[Depends(common_header)])
async def read_item(item_id: int):
    return {"item_id": item_id}
AThe response includes header 'x-token' with the value sent by the client.
BThe response includes header 'x-token' with value 'None'.
CThe response is 422 Unprocessable Entity because header 'x-token' is missing.
DThe response body includes the token value under key 'x_token'.
Attempts:
2 left
💡 Hint

Think about what happens if the required header is missing in the request.

state_output
intermediate
2:00remaining
What is the value of the dependency result in this global dependency example?

Given this FastAPI app, what will be the value of token_value inside the endpoint?

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token():
    return "secret-token"

@app.get("/users/me", dependencies=[Depends(get_token)])
async def read_user(token_value: str = Depends(get_token)):
    return {"token": token_value}
A"secret-token"
BNone
CRaises a runtime error due to duplicate dependency
DEmpty string
Attempts:
2 left
💡 Hint

Consider how FastAPI resolves dependencies when the same function is used globally and locally.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a global dependency in FastAPI?

Choose the correct way to add a global dependency that runs for every request.

Aapp = FastAPI(dependencies=[Depends(common_dep)])
B
app = FastAPI()
@app.global_dependency
async def common_dep(): pass
C
app = FastAPI()
app.add_dependency(common_dep)
D
app = FastAPI()
app.include_dependency(common_dep)
Attempts:
2 left
💡 Hint

Check FastAPI docs for how to add global dependencies at app creation.

🔧 Debug
advanced
2:00remaining
Why does this global dependency not run for the endpoint?

Given this code, why is the global dependency verify_token not executed when calling /open?

FastAPI
from fastapi import FastAPI, Depends

def verify_token():
    print("Token verified")

app = FastAPI(dependencies=[Depends(verify_token)])

@app.get("/open")
async def open_endpoint():
    return {"message": "Open to all"}
ABecause the endpoint does not have any path parameters.
BBecause the global dependency runs but print output is not visible in response.
CBecause the global dependency is only called if the endpoint has a matching parameter.
DBecause the global dependency is ignored for endpoints without explicit Depends in signature.
Attempts:
2 left
💡 Hint

Think about where print output goes in FastAPI apps.

🧠 Conceptual
expert
3:00remaining
How does FastAPI handle multiple global dependencies with overlapping parameters?

Suppose you add two global dependencies that both require a header x-token. How does FastAPI handle this situation?

AFastAPI calls only the first global dependency and skips the second.
BFastAPI requires the header twice and expects two different values.
CFastAPI raises a runtime error due to duplicate header dependencies.
DFastAPI calls both dependencies once each, sharing the same header value from the request.
Attempts:
2 left
💡 Hint

Consider how FastAPI resolves dependencies and parameters from requests.

Practice

(1/5)
1. What is the main purpose of global dependencies in FastAPI?
easy
A. To create database models
B. To define route-specific logic only
C. To style the API responses
D. To run shared logic automatically for every request

Solution

  1. Step 1: Understand what global dependencies do

    Global dependencies are functions or classes that run for every request to apply shared logic.
  2. Step 2: Identify their main use

    They help with tasks like authentication, database connections, or validations that apply to all routes.
  3. Final Answer:

    To run shared logic automatically for every request -> Option D
  4. Quick Check:

    Global dependencies = shared logic for all requests [OK]
Hint: Global dependencies run once per request for all routes [OK]
Common Mistakes:
  • Thinking global dependencies are for styling
  • Confusing global with route-specific dependencies
  • Assuming they create database models
2. Which of the following is the correct way to add a global dependency in FastAPI?
easy
A. app = FastAPI(dependencies=[Depends(common_dependency)])
B. app = FastAPI(global_dep=Depends(common_dependency))
C. app = FastAPI(dependency=common_dependency())
D. app = FastAPI(use_global=common_dependency)

Solution

  1. Step 1: Recall FastAPI global dependency syntax

    Global dependencies are passed as a list to the 'dependencies' parameter when creating the FastAPI app.
  2. Step 2: Match the correct syntax

    app = FastAPI(dependencies=[Depends(common_dependency)]) uses 'dependencies=[Depends(common_dependency)]', which is the correct pattern.
  3. Final Answer:

    app = FastAPI(dependencies=[Depends(common_dependency)]) -> Option A
  4. Quick Check:

    Global dependencies use dependencies=[Depends(...)] [OK]
Hint: Use dependencies=[Depends(...)] in FastAPI() constructor [OK]
Common Mistakes:
  • Using wrong parameter names like global_dep or use_global
  • Calling the dependency function instead of passing Depends()
  • Passing a single dependency without a list
3. Given this code snippet, what will be printed when a request is made to /items/42?
from fastapi import FastAPI, Depends

app = FastAPI()

def common_dep():
    print("Global dependency called")

@app.get("/items/{item_id}")
def read_item(item_id: int, dep=Depends(common_dep)):
    return {"item_id": item_id}
medium
A. No output printed because common_dep is not global
B. Global dependency called printed once per request
C. Global dependency called printed twice per request
D. SyntaxError due to missing global dependency

Solution

  1. Step 1: Check how common_dep is used

    common_dep is used as a route dependency only on the read_item function, not as a global dependency.
  2. Step 2: Understand when common_dep runs

    It runs only when the /items/{item_id} route is called, printing the message once per request to that route.
  3. Final Answer:

    Global dependency called printed once per request -> Option B
  4. Quick Check:

    Route dependency prints only when route is called, not global [OK]
Hint: Route dependencies run per route, not global unless set globally [OK]
Common Mistakes:
  • Assuming common_dep is global when it's route-specific
  • Expecting multiple prints per request
  • Confusing global and route dependencies
4. Identify the error in this FastAPI app code that tries to use a global dependency:
from fastapi import FastAPI, Depends

def common_dep():
    print("Running global dependency")

app = FastAPI(dependencies=Depends(common_dep))
medium
A. common_dep is not defined before use
B. Missing parentheses when calling FastAPI()
C. dependencies parameter expects a list, not a single Depends
D. Depends cannot be used as a global dependency

Solution

  1. Step 1: Check the dependencies parameter type

    The 'dependencies' argument expects a list of Depends instances, not a single Depends object.
  2. Step 2: Identify the fix

    Wrap Depends(common_dep) inside a list: dependencies=[Depends(common_dep)]
  3. Final Answer:

    dependencies parameter expects a list, not a single Depends -> Option C
  4. Quick Check:

    dependencies=[Depends(...)] requires a list [OK]
Hint: Always pass dependencies as a list, even if one item [OK]
Common Mistakes:
  • Passing Depends(...) directly without list
  • Defining dependency after app creation
  • Confusing Depends usage with function call
5. You want to add a global dependency that checks user authentication and also logs request info. Which is the best way to combine these in FastAPI?
hard
A. Add both auth check and logging as separate global dependencies in the dependencies list
B. Add auth check as global dependency and logging inside each route
C. Create one dependency function that calls both auth check and logging, then add it globally
D. Use middleware for auth and global dependency for logging

Solution

  1. Step 1: Understand global dependencies list

    FastAPI allows multiple global dependencies by passing a list to the dependencies parameter.
  2. Step 2: Combine auth and logging as separate dependencies

    Adding both as separate Depends in the list keeps concerns separated and runs both for every request.
  3. Step 3: Evaluate other options

    Create one dependency function that calls both auth check and logging, then add it globally mixes concerns in one function, B is inconsistent, D mixes middleware and dependencies unnecessarily.
  4. Final Answer:

    Add both auth check and logging as separate global dependencies in the dependencies list -> Option A
  5. Quick Check:

    Multiple global dependencies = dependencies=[Depends(...), Depends(...)] [OK]
Hint: Use a list of Depends for multiple global dependencies [OK]
Common Mistakes:
  • Combining unrelated logic in one dependency
  • Using middleware instead of dependencies for all tasks
  • Adding some logic only per route, not globally