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
Using Sub-dependencies in FastAPI
📖 Scenario: You are building a simple FastAPI app that needs to check user authentication and then get user details. To keep your code clean, you want to use sub-dependencies: one dependency to check authentication, and another that depends on it to get user info.
🎯 Goal: Build a FastAPI app with two dependencies: get_current_user that depends on verify_token. The app should have one route /profile that returns the current user's name.
📋 What You'll Learn
Create a dependency function called verify_token that returns a fixed token string.
Create a sub-dependency function called get_current_user that depends on verify_token and returns a dictionary with a name key.
Create a FastAPI app instance called app.
Create a GET route /profile that uses get_current_user as a dependency and returns the user's name.
💡 Why This Matters
🌍 Real World
In real apps, authentication and user info fetching are often done with dependencies. Sub-dependencies help organize these steps cleanly.
💼 Career
Understanding FastAPI dependencies and sub-dependencies is essential for backend developers building secure and maintainable APIs.
Progress0 / 4 steps
1
Create the verify_token dependency
Create a function called verify_token that returns the string 'secrettoken123'.
FastAPI
Hint
This function simulates checking a token and returns a fixed string.
2
Create the get_current_user sub-dependency
Create a function called get_current_user that takes a parameter token with a dependency on verify_token using Depends. It should return a dictionary {'name': 'Alice'}.
FastAPI
Hint
Use Depends(verify_token) to declare the sub-dependency.
3
Create the FastAPI app instance
Import FastAPI and create an app instance called app.
FastAPI
Hint
Remember to import FastAPI and create app = FastAPI().
4
Create the /profile route using the sub-dependency
Create a GET route /profile on app that uses get_current_user as a dependency with Depends. The route function should accept a parameter user and return {'user_name': user['name']}.
FastAPI
Hint
Use @app.get('/profile') and Depends(get_current_user) to inject the user.
Practice
(1/5)
1. What is the main purpose of sub-dependencies in FastAPI?
easy
A. To handle HTTP requests directly
B. To create database connections only
C. To reuse small parts of code inside other dependencies
D. To replace middleware functions
Solution
Step 1: Understand what sub-dependencies do
Sub-dependencies allow you to reuse small parts of code inside other dependencies, making your code cleaner.
Step 2: Compare options with this purpose
Only To reuse small parts of code inside other dependencies correctly describes this purpose; others describe unrelated tasks.
Final Answer:
To reuse small parts of code inside other dependencies -> Option C
Quick Check:
Sub-dependencies = Reuse code [OK]
Hint: Sub-dependencies help reuse code inside dependencies [OK]
Assuming sub-dependencies only manage database connections
2. Which of the following is the correct way to declare a sub-dependency in FastAPI?
easy
A. def sub_dep(): return 'data'
def main_dep(sub: str = Depends(sub_dep)): return sub
B. def sub_dep(): return 'data'
def main_dep(sub: str = sub_dep()): return sub
C. def sub_dep(): return 'data'
def main_dep(sub: str = Depends(sub_dep())): return sub
D. def sub_dep(): return 'data'
def main_dep(sub: str): return sub
Solution
Step 1: Recall FastAPI dependency syntax
Dependencies must be passed as functions inside Depends(), not called directly.
Step 2: Analyze each option
def sub_dep(): return 'data'
def main_dep(sub: str = Depends(sub_dep)): return sub correctly uses Depends(sub_dep) without calling it. Options B and C call the function, which is incorrect. def sub_dep(): return 'data'
def main_dep(sub: str): return sub lacks Depends entirely.
Final Answer:
def sub_dep(): return 'data'\n\ndef main_dep(sub: str = Depends(sub_dep)): return sub -> Option A
Quick Check:
Use Depends(function) without parentheses [OK]
Hint: Use Depends with function name, no parentheses [OK]
Common Mistakes:
Calling the dependency function inside Depends()
Not using Depends at all
Passing the function call result instead of the function
3. Given the code below, what will be the output when calling /items/42?
A. Calling main_dep() inside Depends instead of passing the function
B. Missing return statement in sub_dep
C. Incorrect route path syntax
D. Using async def for endpoint without await
Solution
Step 1: Identify how Depends should be used
Depends expects a function reference, not a function call. Calling main_dep() executes it immediately, which is wrong.
Step 2: Check the code for this mistake
The code uses Depends(main_dep()), which calls the function instead of passing it. It should be Depends(main_dep).
Final Answer:
Calling main_dep() inside Depends instead of passing the function -> Option A
Quick Check:
Depends needs function, not function call [OK]
Hint: Pass function to Depends, don't call it [OK]
Common Mistakes:
Calling dependency functions inside Depends()
Confusing async usage with dependency errors
Ignoring Depends syntax rules
5. You want to create a FastAPI endpoint that depends on a main dependency which itself depends on two sub-dependencies. How should you structure the dependencies to ensure both sub-dependencies are called and their results used in the main dependency?
hard
A. Call both sub-dependencies inside main dependency without Depends()
B. Pass sub-dependencies as global variables to main dependency
C. Use a single sub-dependency that returns a tuple of both results
D. Define two sub-dependency functions, then in main dependency use Depends() for both as parameters
Solution
Step 1: Understand sub-dependency usage in main dependency
FastAPI allows multiple dependencies by declaring parameters with Depends(). To use two sub-dependencies, declare both as parameters with Depends().
Step 2: Evaluate options for correctness
Define two sub-dependency functions, then in main dependency use Depends() for both as parameters correctly describes this pattern. Call both sub-dependencies inside main dependency without Depends() misses Depends(), so sub-dependencies won't be injected. Use a single sub-dependency that returns a tuple of both results is possible but less clear and not standard. Pass sub-dependencies as global variables to main dependency is incorrect as global variables don't work for dependency injection.
Final Answer:
Define two sub-dependency functions, then in main dependency use Depends() for both as parameters -> Option D