Complete the code to declare a class-based dependency in FastAPI.
from fastapi import Depends, FastAPI class CommonQueryParams: def __init__(self, q: str = None): self.q = q app = FastAPI() @app.get("/items/") async def read_items(commons: CommonQueryParams = Depends([1])): return {"q": commons.q}
In FastAPI, to use a class as a dependency, you pass the class itself (not an instance) to Depends(). FastAPI will create an instance automatically.
Complete the code to inject a class-based dependency into a path operation.
from fastapi import Depends, FastAPI class User: def __init__(self, username: str): self.username = username app = FastAPI() @app.get("/users/me") async def read_user(user: User = Depends([1])): return {"username": user.username}
Pass the class name to Depends without parentheses. FastAPI will create the instance and inject it.
Fix the error in the class-based dependency usage.
from fastapi import Depends, FastAPI class Settings: def __init__(self): self.debug = True app = FastAPI() @app.get("/settings") async def get_settings(settings: Settings = Depends([1])): return {"debug": settings.debug}
Pass the class name to Depends without parentheses. FastAPI will instantiate it automatically.
Fill both blanks to create a class-based dependency that accepts a query parameter and use it in a path operation.
from fastapi import Depends, FastAPI class QueryParams: def __init__(self, q: str = None): self.q = q app = FastAPI() @app.get("/search") async def search(params: QueryParams = Depends([1])): return {"query": params.[2]
Pass the class name to Depends. The instance has an attribute 'q' holding the query parameter.
Fill all three blanks to create a class-based dependency with two parameters and use them in a path operation.
from fastapi import Depends, FastAPI class Pagination: def __init__(self, skip: int = 0, limit: int = 10): self.skip = skip self.limit = limit app = FastAPI() @app.get("/items") async def list_items(pagination: Pagination = Depends([1])): return {"skip": pagination.[2], "limit": pagination.[3]
Pass the class name to Depends. Access the 'skip' and 'limit' attributes from the instance.