Implement FastAPI Dependency Injection for Database and Auth Layers
Build a full FastAPI dependency injection architecture covering database sessions, JWT auth, RBAC, pagination, and service layers.
๐ The Prompt
Create a comprehensive FastAPI dependency injection setup in Python for a [APPLICATION_DOMAIN] application that cleanly separates concerns across database access, authentication, and authorization.
**Dependencies to Implement:**
1. **Database Session (`get_db`)**: Yield an async SQLAlchemy session from a session factory. Ensure proper commit/rollback/close lifecycle. Use `AsyncSession` with [DATABASE_TYPE] (e.g., PostgreSQL, SQLite).
2. **Current User (`get_current_user`)**: Depend on a bearer token extracted via `OAuth2PasswordBearer`. Decode the [TOKEN_TYPE] token (JWT/opaque), validate claims (`exp`, `sub`, `iss`), and return a `UserSchema` object. Raise `HTTPException(401)` with a `WWW-Authenticate` header on failure.
3. **Role-Based Authorization (`require_role`)**: Create a parameterized dependency factory that accepts `allowed_roles: list[str]`. It should depend on `get_current_user` and raise `HTTPException(403)` if the user's role is not in the allowed list. Include a clear error message indicating the required role.
4. **Pagination (`get_pagination`)**: Extract `page` and `page_size` from query parameters with defaults of [DEFAULT_PAGE] and [DEFAULT_PAGE_SIZE]. Validate max `page_size` of [MAX_PAGE_SIZE]. Return a `PaginationParams` dataclass.
5. **Service Layer (`get_[SERVICE_NAME]_service`)**: Inject the DB session into a service class `[SERVICE_NAME]Service` that encapsulates business logic for [BUSINESS_ENTITY].
**Deliverables:**
- `dependencies/` module with each dependency in its own file
- Pydantic schemas for `UserSchema` and `PaginationParams`
- One example router demonstrating all dependencies wired together on a `GET /[ENDPOINT_PATH]` endpoint
- Pytest fixtures that override dependencies for testing
Follow FastAPI best practices: use `Annotated` type hints (Python 3.10+), async/await throughout, and proper typing.
๐ก Tips for Better Results
Fill in [APPLICATION_DOMAIN] and [BUSINESS_ENTITY] with your actual domain (e.g., 'e-commerce' and 'Product') to get contextually relevant service layer code. Always request pytest override fixtures โ testing DI-heavy FastAPI apps without them is painful. Specify Python 3.10+ to get modern Annotated[] syntax.
๐ฏ Use Cases
Python backend developers use this when architecting a new FastAPI project that needs clean separation between auth, data access, and business logic layers.