What is the main benefit of using dependency injection in FastAPI applications?
Think about how dependency injection helps with reusing and testing parts of your app.
Dependency injection lets FastAPI provide needed components like database sessions or settings automatically. This makes code cleaner, easier to test, and avoids manual setup everywhere.
Given this FastAPI endpoint using dependency injection, what will be the output when accessed?
from fastapi import FastAPI, Depends
app = FastAPI()
def get_number():
return 42
@app.get("/number")
async def read_number(num: int = Depends(get_number)):
return {"number": num}Consider what the Depends function does to the parameter num.
The Depends(get_number) tells FastAPI to call get_number and pass its return value (42) as the num parameter. So the endpoint returns {"number": 42}.
In FastAPI, when does a dependency function get executed during a request?
Think about when the endpoint needs the data from the dependency.
FastAPI calls dependency functions before the endpoint runs so it can pass their results as arguments. This ensures the endpoint has all needed data upfront.
Which option correctly uses dependency injection to provide a database session to a FastAPI endpoint?
from fastapi import Depends def get_db(): db = "db_session" try: yield db finally: pass # close db @app.get("/items") async def read_items(db = ???): return {"db": db}
Remember that Depends expects a function, not a function call.
Using Depends(get_db) tells FastAPI to call get_db and inject its result. Calling get_db() directly or passing Depends(get_db()) is incorrect syntax.
Consider this code snippet:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_value():
return 10
@app.get("/value")
async def read_value(val: int = Depends(get_value())):
return {"val": val}What error will this code cause when starting the app?
Look carefully at how Depends is used with parentheses.
The code calls get_value() immediately and passes its result (an int) to Depends, which expects a callable function. This causes a TypeError.