What is dependency injection with classes and factories in FastAPI?
Answer
FastAPI's dependency system supports three patterns. Functions (basic): def get_db(): yield session. Classes with __call__: create stateful, configurable dependencies: class PaginationParams: def __init__(self, page: int = 1, size: int = 20): self.page = page; self.size = size; @app.get('/items') async def list_items(pagination: PaginationParams = Depends()): ... — FastAPI instantiates the class with query params automatically when using Depends() without arguments on a class. Factory functions: create dependencies with configuration: def get_permission_checker(required: str): async def check(user: User = Depends(get_user)): if required not in user.permissions: raise HTTPException(403); return user; return check. Usage: @app.delete('/admin', dependencies=[Depends(get_permission_checker('admin'))]). This enables reusable, composable authorization dependencies with parameterized behavior.
More FastAPI / Flask Questions
View all →- Advanced What is FastAPI's OpenAPI specification and how is it customized?
- Advanced How do you implement event-driven patterns in FastAPI with Kafka or Redis?
- Advanced What are advanced Pydantic features for complex validation?
- Advanced How do you implement a multi-tenant API with FastAPI?
- Advanced What is the strangler fig pattern for migrating Flask to FastAPI?