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.

๐Ÿ”— Related Prompts

๐Ÿ’ป Coding beginner

Explain Code Like Im a Beginner

Get any code explained in plain English with line-by-line breakdowns, analogies, and learning suggestions.

๐Ÿ’ป Coding beginner

Debug My Code and Explain the Fix

Get your code debugged with clear explanations of what went wrong and why, plus the corrected version.

๐Ÿ’ป Coding intermediate

Write Unit Tests for My Code

Generate thorough unit tests covering edge cases, error handling, and both positive and negative scenarios.

๐Ÿ’ป Coding intermediate

Convert Code Between Languages

Convert code between any programming languages while maintaining idiomatic patterns and best practices.

๐Ÿ’ป Coding intermediate

Write a REST API Endpoint

Generate production-ready REST API endpoints with validation, error handling, and documentation.

๐Ÿ’ป Coding advanced

Create a GitHub Actions CI/CD Workflow for Automated Testing and Deployment

Generate a complete GitHub Actions CI/CD workflow with build, test, deploy, and notification jobs for your project.