Skip to main content

FastAPI Prompt Templates

Cập nhật: 03/2026


Essential Aspects & Templates

1. Basic API Endpoints

<role>Python backend developer chuyên FastAPI</role>

<action>
Tạo FastAPI endpoint để [CHỨC_NĂNG]
</action>

<context>
- Method: [GET/POST/PUT/DELETE]
- Path: [URL_PATH]
- API version: [v1/v2]
- Request body: [STRUCTURE] (nếu POST/PUT)
- Response model: [STRUCTURE]
- Business logic: [MÔ_TẢ]
- Cần đọc existing routers để học patterns
</context>

<expectation>
- APIRouter instance: router = APIRouter(prefix="/[resource]", tags=["[Resource]"])
- Mount với version prefix trong main.py:
app.include_router(router, prefix="/api/v1")
- Async function: async def [endpoint_name](...) -> [ResponseModel]
- Type hints cho parameters và return
- Pydantic models cho request/response
- Status codes: @router.post(..., status_code=201)
- Dependencies: db: AsyncSession = Depends(get_db)
- Error handling: raise HTTPException(status_code=404)
- File structure:
app/
├── api/
│ ├── v1/
│ │ ├── __init__.py
│ │ └── [resource].py ← file này
│ └── v2/ ← future versions
└── main.py
</expectation>

2. Pydantic Models & Validation

<role>Python developer chuyên data validation</role>

<action>
Tạo Pydantic models cho [RESOURCE] với validation rules
</action>

<context>
- Resource: [TÊN_RESOURCE]
- Fields: [LIỆT_KÊ_FIELDS]
- Validation: [RULES]
- Use cases: [CREATE/UPDATE/RESPONSE/IN_DB]
- Relationships: [NESTED_MODELS]
</context>

<expectation>
- Separate models: [Resource]Create, [Resource]Update, [Resource]Response
- BaseModel với Field() constraints:
• Field(..., min_length=, max_length=)
• Field(..., ge=, le=, gt=, lt=)
• Field(..., regex=)
- Custom validation: @field_validator('field_name')
- Cross-field validation: @model_validator
- Config: model_config = ConfigDict(from_attributes=True)
- Examples: model_config examples cho OpenAPI
- File: app/schemas/[resource].py
</expectation>

3. SQLAlchemy 2.0 Async ORM

<role>Database engineer chuyên SQLAlchemy async</role>

<action>
Setup SQLAlchemy 2.0 async models và database session cho [PROJECT]
</action>

<context>
- Database: [POSTGRESQL/MYSQL]
- Driver: [asyncpg/aiomysql]
- Models: [LIỆT_KÊ_MODELS]
- Relationships: [ONE_TO_MANY/MANY_TO_MANY]
- Migrations: Alembic
</context>

<expectation>
Database setup (app/core/database.py):
- AsyncEngine: create_async_engine(DATABASE_URL)
- async_sessionmaker: async_sessionmaker(engine, expire_on_commit=False)
- DeclarativeBase class
- get_db dependency: async generator với yield

Models (app/models/[resource].py):
- mapped_column() thay vì Column()
- Type hints: Mapped[int], Mapped[str]
- Relationships: relationship(lazy="selectin")
- Proper indexes: __table_args__

Alembic:
- alembic init
- env.py config cho async
- Migrations: alembic revision --autogenerate
</expectation>

4. Dependency Injection

<role>FastAPI architect chuyên DI patterns</role>

<action>
Tạo reusable dependencies cho [USE_CASES]
</action>

<context>
- Dependencies: [PAGINATION/AUTH/DB_SESSION/SERVICES]
- Scope: [REQUEST/APPLICATION]
- Nested: [YES/NO]
- Cleanup: [YES/NO]
</context>

<expectation>
Dependencies file (app/dependencies.py):
- Async functions với type hints
- Yield dependencies: async def get_db() -> AsyncGenerator[AsyncSession, None]
- Dependency classes cho stateful dependencies
- Common patterns:
• get_current_user: JWT validation
• pagination_params: skip, limit
• get_db: database session

Usage:
- Function parameters: user: User = Depends(get_current_user)
- Annotated types: user: Annotated[User, Depends(get_current_user)]
- Nested dependencies supported
</expectation>

5. JWT Authentication

<role>Security engineer chuyên FastAPI auth</role>

<action>
Implement JWT authentication system với [REGISTRATION/LOGIN/PROTECTED_ROUTES]
</action>

<context>
- Auth flow: register → login → access token → protected endpoints
- Token type: JWT với HS256
- Password hashing: bcrypt
- User model: id, email, hashed_password, is_active
- Token expiry: 30 minutes
</context>

<expectation>
Security utilities (app/core/security.py):
- hash_password(password: str) -> str
- verify_password(plain: str, hashed: str) -> bool
- create_access_token(data: dict) -> str
- decode_token(token: str) -> dict

Auth endpoints (app/routers/auth.py):
- POST /auth/register: hash password, create user, return 201
- POST /auth/login: verify credentials, return JWT access_token

Dependencies:
- OAuth2PasswordBearer: tokenUrl="auth/login"
- get_current_user: decode token, fetch user, return User

Protected routes:
- current_user: User = Depends(get_current_user)

Environment:
- SECRET_KEY từ .env (KHÔNG hardcode)
</expectation>

6. Error Handling

<role>Senior Python developer chuyên error handling</role>

<action>
Setup custom exceptions và handlers cho [APPLICATION]
</action>

<context>
- Exception types: [NOT_FOUND/VALIDATION/CONFLICT/UNAUTHORIZED]
- Error format: consistent JSON structure
- Logging: [YES/NO]
- Stack traces: only in debug mode
</context>

<expectation>
Custom exceptions (app/exceptions.py):
- HTTPException subclasses
- NotFoundError(resource, id)
- ConflictError(message)
- ValidationError(field, message)

Exception handlers (app/main.py):
- @app.exception_handler(CustomException)
- Return format: {"detail": str, "code": str, "timestamp": datetime}
- Log errors trước khi return
- KHÔNG expose internal errors to users

Usage:
- raise NotFoundError("User", user_id)
- FastAPI converts to proper HTTP response
</expectation>

7. Background Tasks

<role>FastAPI developer chuyên async operations</role>

<action>
Implement background task [TÊN_TASK] để [CHỨC_NĂNG]
</action>

<context>
- Task: [SEND_EMAIL/PROCESS_FILE/UPDATE_CACHE]
- Trigger: [AFTER_RESPONSE/SCHEDULED]
- Duration: [SHORT/LONG]
- Tool: [BACKGROUND_TASKS/CELERY]
</context>

<expectation>
FastAPI BackgroundTasks (for short tasks):
- Import BackgroundTasks
- Add parameter: background_tasks: BackgroundTasks
- background_tasks.add_task(function, *args)
- Async task function: async def send_email(...)

Celery (for long tasks):
- celery_app.py: Celery instance
- @celery_app.task decorator
- Trigger: task.delay(*args)
- Monitor: Celery worker + Flower
- Redis broker: CELERY_BROKER_URL

Choose based on duration:
- <5s: BackgroundTasks
- >5s: Celery
</expectation>

8. Testing

<role>QA Engineer chuyên FastAPI testing</role>

<action>
Viết tests cho [ENDPOINTS/SERVICES] với pytest
</action>

<context>
- Test type: [UNIT/INTEGRATION]
- Endpoints: [LIỆT_KÊ_ENDPOINTS]
- Database: [TEST_DB/IN_MEMORY_SQLITE]
- Auth: [MOCK_JWT/REAL_AUTH]
- Coverage target: >= 80%
</context>

<expectation>
Setup (tests/conftest.py):
- pytest fixtures: test_app, test_client, test_db
- Override dependencies: app.dependency_overrides
- TestClient từ fastapi.testclient
- Database cleanup: truncate after each test

Test structure (tests/test_[router].py):
- Arrange-Act-Assert pattern
- def test_[scenario]:
- Test cases:
• Happy path: valid data → 200/201
• Validation: invalid data → 422
• Auth: no token → 401, wrong token → 403
• Not found: nonexistent resource → 404
- Async tests: @pytest.mark.asyncio
- Coverage: pytest --cov=app --cov-report=html
</expectation>

9. Configuration

<role>DevOps engineer chuyên configuration management</role>

<action>
Setup environment configuration với pydantic-settings
</action>

<context>
- Environments: [DEVELOPMENT/STAGING/PRODUCTION]
- Secrets: [DATABASE_URL/SECRET_KEY/API_KEYS]
- Config types: [APP/DATABASE/AUTH/EXTERNAL_SERVICES]
</context>

<expectation>
Settings class (app/core/config.py):
- from pydantic_settings import BaseSettings
- class Settings(BaseSettings):
- Fields với types và defaults
- model_config = SettingsConfigDict(env_file=".env")
- Nested configs: DatabaseSettings, AuthSettings
- Validation: Field(..., min_length=32) cho SECRET_KEY

Usage:
- settings = Settings() (singleton)
- Access: settings.DATABASE_URL
- Type-safe: autocomplete works

Environment files:
- .env (local, gitignored)
- .env.example (committed, no secrets)
- Environment variables override .env
</expectation>

10. Performance & Caching

<role>Performance engineer chuyên optimization</role>

<action>
Implement caching layer với Redis cho [ENDPOINTS]
</action>

<context>
- Endpoints: [HIGH_TRAFFIC_ENDPOINTS]
- Cache strategy: [CACHE_ASIDE/WRITE_THROUGH]
- TTL: [SECONDS]
- Invalidation: [ON_UPDATE/ON_DELETE/TIME_BASED]
</context>

<expectation>
Redis setup (app/core/cache.py):
- import redis.asyncio as redis
- Redis client pool
- get_redis dependency

Cache patterns:
- Cache key: f"{prefix}:{resource}:{id}"
- GET: check cache → miss → query DB → set cache → return
- POST/PUT/DELETE: invalidate related caches
- Serialization: json.dumps/loads hoặc pickle
- TTL: ex=3600 (1 hour)

Usage:
- cache_key = f"user:{user_id}"
- cached = await redis.get(cache_key)
- if cached: return json.loads(cached)
- # ... fetch from DB
- await redis.set(cache_key, json.dumps(data), ex=3600)
</expectation>

11. Production Deployment

<role>DevOps engineer chuyên FastAPI deployment</role>

<action>
Setup production deployment cho FastAPI application
</action>

<context>
- Server: [GUNICORN/UVICORN_WORKERS]
- Container: [DOCKER/KUBERNETES]
- Reverse proxy: [NGINX/TRAEFIK]
- Database migrations: Alembic
</context>

<expectation>
Gunicorn + Uvicorn:
- gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
- Workers: 2-4 × CPU cores
- Worker class: UvicornWorker (async support)

Docker:
- Dockerfile: multi-stage build
- Base image: python:3.11-slim
- Install dependencies: requirements.txt
- Run: CMD ["gunicorn", ...]

Environment:
- .env.production với production values
- Secrets từ environment variables
- DEBUG=False trong production

Health checks:
- GET /health endpoint
- Return 200 với {"status": "healthy"}

Logging:
- Structured logging (JSON format)
- Log level: INFO trong production
- No sensitive data trong logs
</expectation>

Best Practices Checklist

  • ✅ Python 3.11+ với type hints
  • ✅ Async/await cho I/O operations
  • ✅ Pydantic V2 models
  • ✅ SQLAlchemy 2.0 async
  • ✅ Environment variables (pydantic-settings)
  • ✅ JWT authentication
  • ✅ Custom exceptions
  • ✅ Testing với pytest >= 80% coverage
  • ✅ OpenAPI docs với examples
  • ✅ Production-ready deployment