0
0
FastAPIframework~30 mins

Sub-dependencies in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use @app.get('/profile') and Depends(get_current_user) to inject the user.