Shared dependencies let you reuse code easily in different parts of your FastAPI app. This helps keep your code clean and simple.
Shared dependencies in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends app = FastAPI() def common_dependency(): # code to run return "value" @app.get("/items/") async def read_items(dep=Depends(common_dependency)): return dep
Use Depends() to declare a dependency in your path operation function.
FastAPI will run the dependency function and pass its result to your endpoint.
from fastapi import FastAPI, Depends app = FastAPI() def get_token_header(): return "token123" @app.get("/users/") async def read_users(token: str = Depends(get_token_header)): return {"token": token}
from fastapi import FastAPI, Depends app = FastAPI() def common_parameters(q: str = None): return {"q": q} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return commons
This program shows a shared database connection dependency used in two routes. Both routes get the same 'db' value from get_db.
from fastapi import FastAPI, Depends app = FastAPI() def get_db(): db = "database connection" try: yield db finally: pass # close connection here @app.get("/users/") async def read_users(db=Depends(get_db)): return {"db": db, "message": "Users fetched"} @app.get("/items/") async def read_items(db=Depends(get_db)): return {"db": db, "message": "Items fetched"}
Dependencies can be functions or classes.
Use yield in dependencies to handle setup and cleanup (like opening and closing a database connection).
Shared dependencies help keep your code DRY (Don't Repeat Yourself).
Shared dependencies let you reuse code across multiple routes.
Use Depends() to declare dependencies in FastAPI.
They help keep your app clean and easy to maintain.
Practice
Depends() in FastAPI for shared dependencies?Solution
Step 1: Understand the role of
Depends()Depends()is used in FastAPI to declare dependencies that can be shared across multiple routes.Step 2: Identify the main benefit
Using shared dependencies helps reuse code and keep the app clean and maintainable.
Final Answer:
To reuse code across multiple routes by declaring common dependencies -> Option AQuick Check:
Shared dependencies = reuse code [OK]
- Thinking Depends() creates routes
- Confusing Depends() with response models
- Assuming Depends() manages database connections directly
Solution
Step 1: Review correct dependency syntax
In FastAPI, dependencies are declared usingDepends(function_name)inside the function parameters.Step 2: Check each option
def get_db(): return Session(); @app.get('/items') def read_items(db=Depends(get_db)): pass correctly usesdb=Depends(get_db). def get_db(): return Session(); @app.get('/items') def read_items(db=get_db()): pass calls the function directly, which is incorrect. def get_db(): return Session(); @app.get('/items') def read_items(db: Session): pass lacks Depends, so no injection happens. def get_db(): return Session(); @app.get('/items') def read_items(db=Depends()): pass uses Depends without a function, which is invalid.Final Answer:
def get_db(): return Session(); @app.get('/items') def read_items(db=Depends(get_db)): pass -> Option AQuick Check:
Depends() needs function inside [OK]
- Calling dependency function directly in parameter
- Forgetting to use Depends() wrapper
- Using Depends() without specifying the function
/items/42?
from fastapi import FastAPI, Depends
app = FastAPI()
def common_dep():
return "shared value"
@app.get('/items/{item_id}')
def read_item(item_id: int, value: str = Depends(common_dep)):
return {"item_id": item_id, "value": value}Solution
Step 1: Understand dependency injection
The functioncommon_depreturns the string "shared value". FastAPI injects this into thevalueparameter viaDepends(common_dep).Step 2: Check the returned JSON
The route returns a dictionary withitem_idfrom the path andvaluefrom the dependency. So the output will be{"item_id": 42, "value": "shared value"}.Final Answer:
{"item_id": 42, "value": "shared value"} -> Option DQuick Check:
Dependency injects "shared value" [OK]
- Assuming dependency returns item_id
- Expecting error due to missing parameter
- Thinking value will be null without explicit call
from fastapi import FastAPI, Depends
app = FastAPI()
def get_token():
return "token123"
@app.get('/secure')
def secure_route(token: str = Depends()):
return {"token": token}Solution
Step 1: Check Depends usage
The parametertokenusesDepends()without specifying the dependency function. This is incorrect syntax.Step 2: Correct usage
Depends must wrap the function providing the dependency, so it should beDepends(get_token).Final Answer:
Depends() is missing the dependency function inside -> Option CQuick Check:
Depends() needs function argument [OK]
- Using Depends() without argument
- Expecting Depends() to work without function
- Confusing Depends() with decorator syntax
Solution
Step 1: Understand dependency cleanup
FastAPI supports dependencies with cleanup by usingyieldinside the dependency function. This allows setup before yield and cleanup after.Step 2: Apply to database session
The correct pattern is to create the session, yield it for use in routes, then close it after the request finishes.Final Answer:
Use a dependency function withyieldthat creates the session, yields it, then closes it after -> Option BQuick Check:
Yield in dependency = setup and cleanup [OK]
- Reusing global session without closing
- Closing session inside route instead of dependency
- Not using Depends() for session injection
