0
0
FastAPIframework~10 mins

Why dependency injection matters in FastAPI - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BResponse
CRequest
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Depends instead of FastAPI
Using Request or Response instead of FastAPI
2fill in blank
medium

Complete the code to declare a dependency using Depends.

FastAPI
from fastapi import Depends

app = FastAPI()

def get_token():
    return "token123"

@app.get("/items")
def read_items(token: str = [1](get_token)):
    return {"token": token}
Drag options to blanks, or click blank then click option'
ADepends
BRequest
CResponse
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of Depends
Not wrapping the dependency function
3fill in blank
hard

Fix the error in the dependency injection to correctly inject the database session.

FastAPI
from fastapi import Depends

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users")
def read_users(db: Session = [1](get_db)):
    return db.query(User).all()
Drag options to blanks, or click blank then click option'
ARequest
BDepends
CFastAPI
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use Depends causes runtime errors
Using Request or Response instead of Depends
4fill in blank
hard

Fill both blanks to create a reusable dependency and inject it into the route.

FastAPI
from fastapi import Depends

app = FastAPI()

def common_parameters(q: str = None, limit: int = 10):
    return {"q": q, "limit": limit}

@app.get("/search")
def search(params: dict = [1](common_parameters)):
    return params if params[[2]] else {"limit": 10}
Drag options to blanks, or click blank then click option'
ADepends
B"q"
C"limit"
DRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of Depends
Using wrong dictionary keys
5fill in blank
hard

Fill all three blanks to declare a dependency with parameters and use it in a route.

FastAPI
from fastapi import Depends

app = FastAPI()

def pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

@app.get("/items")
def get_items(p: dict = [1](pagination)):
    return {"skip": p[[2]], "limit": p[[3]]}
Drag options to blanks, or click blank then click option'
ADepends
B"skip"
C"limit"
D"page"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys like "page"
Not using Depends to inject the dependency