HTTP & REST API với FastAPI: Pydantic v2, dependency injection, lỗi chuẩn
Xây REST API đúng chuẩn bằng FastAPI: route và router theo tính năng, schema request/response bằng Pydantic v2, dependency injection với Depends, phân trang cursor, xử lý lỗi nhất quán, OpenAPI tự sinh, async đúng chỗ.
FastAPI là framework API Python tăng trưởng nhanh nhất và xuất hiện dày trong JD backend/AI năm 2026. Nó cho tài liệu
OpenAPI và validate tự động — nhưng cũng dễ tạo API tệ: trả thẳng ORM object, một file main.py 2000 dòng, endpoint
async gọi thư viện đồng bộ. Status code, cấu trúc lỗi và cách tổ chức router là những thứ reviewer nhìn đầu tiên.
🎯 Mục tiêu học tập
- Tổ chức ứng dụng FastAPI theo tính năng với APIRouter
- Định nghĩa schema request/response riêng bằng Pydantic v2, tách khỏi model DB
- Dùng Depends cho session DB, người dùng hiện tại, phân quyền, phân trang
- Trả lỗi theo một định dạng thống nhất với exception handler
- Dùng đúng def vs async def; tài liệu OpenAPI rõ ràng
Cấu trúc dự án
src/taskflow/
├── main.py # tạo app, gắn router, middleware, exception handler, lifespan
├── core/ (config.py, db.py, security.py, errors.py)
├── modules/
│ └── projects/
│ ├── router.py # HTTP: nhận schema, gọi service, trả schema
│ ├── schemas.py # Pydantic: ProjectCreate, ProjectOut
│ ├── service.py # nghiệp vụ, không biết HTTP
│ ├── repository.py # truy vấn SQLAlchemy
│ └── models.py # SQLAlchemy model
└── tests/
@asynccontextmanager
async def lifespan(app: FastAPI):
await db.connect() # khởi tạo pool, client HTTP dùng chung
yield
await db.disconnect() # dọn dẹp khi tắt (graceful shutdown)
app = FastAPI(title="TaskFlow API", version="1.0.0", lifespan=lifespan)
app.include_router(projects.router, prefix="/v1/projects", tags=["projects"])
Pydantic v2: schema tại biên
from pydantic import BaseModel, ConfigDict, Field, field_validator
from datetime import datetime
class TaskCreate(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) # field lạ → 422 (chống mass assignment)
title: str = Field(min_length=1, max_length=200)
assignee_id: int | None = None
due_at: datetime | None = None
@field_validator("due_at")
@classmethod
def not_in_past(cls, v: datetime | None) -> datetime | None:
if v and v < datetime.now(v.tzinfo):
raise ValueError("Hạn chót phải ở tương lai")
return v
class TaskOut(BaseModel):
model_config = ConfigDict(from_attributes=True) # đọc từ ORM object
id: str
title: str
status: TaskStatus
created_at: datetime
Schema vào và ra tách biệt, và tách khỏi model DB: không lộ cột nội bộ, đổi schema DB không làm vỡ client.
Pydantic v2 (lõi viết bằng Rust) nhanh hơn v1 nhiều lần; khai báo response_model để FastAPI lọc dữ liệu trả về.
Dependency injection với Depends
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session
async def current_user(token: Annotated[str, Depends(oauth2_scheme)], s: Annotated[AsyncSession, Depends(get_session)]) -> User:
user = await auth.user_from_token(s, token)
if not user:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
return user
SessionDep = Annotated[AsyncSession, Depends(get_session)]
UserDep = Annotated[User, Depends(current_user)]
@router.post("", response_model=TaskOut, status_code=201)
async def create_task(project_id: int, body: TaskCreate, session: SessionDep, user: UserDep) -> Task:
project = await projects.get_for_user(session, project_id, user) # 404 nếu không thuộc tổ chức của user
return await tasks.create(session, project, body, actor=user)
- Dependency được cache trong một request; test thay thế bằng
app.dependency_overrides. - Đặt logic quyền vào dependency/service tái sử dụng, không lặp ở từng endpoint.
Phân trang, lỗi chuẩn, def vs async def
class Page[T](BaseModel):
data: list[T]
next_cursor: str | None
class AppError(Exception):
def __init__(self, status: int, code: str, message: str, details: dict | None = None):
self.status, self.code, self.message, self.details = status, code, message, details
@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError):
return JSONResponse(status_code=exc.status, media_type="application/problem+json", content={
"type": f"https://api.example.com/errors/{exc.code}", "title": exc.message,
"status": exc.status, "code": exc.code, "details": exc.details,
"request_id": request.state.request_id,
})
- 401/403/404/409/422/429 đúng ngữ nghĩa; lỗi validate của FastAPI mặc định 422 — định dạng lại cho thống nhất nếu cần.
- Không trả stack trace; log lỗi không lường trước kèm request_id.
async defkhi mọi I/O bên trong là async;defkhi dùng thư viện đồng bộ (FastAPI chạy trong threadpool). Trộn sai là nguồn treo hệ thống (Module 3).- Cursor pagination cho danh sách lớn; giới hạn
limittối đa.
🏋️ Bài tập thực hành
Xây REST API cho Organization → Project → Task bằng FastAPI: CRUD, gán người, đổi trạng thái theo enum, archive. Yêu cầu:
router theo tính năng, schema Pydantic vào/ra riêng (extra="forbid"), service tách khỏi HTTP, Depends cho session/user,
cursor pagination, một định dạng lỗi, OpenAPI tại /docs có mô tả và ví dụ, test bằng httpx AsyncClient cho
các status code 200/201/401/404/422. Tạm lưu dữ liệu trong bộ nhớ qua repository interface (Module 6 thay bằng PostgreSQL).
📚 Tài nguyên học tập
-
FastAPI DocumentationTài liệu chính thức, đọc hết Tutorial và AdvancedDocs
-
Pydantic v2Validate dữ liệu và schemaDocs
-
FastAPI best practices (zhanymkanov)Quy ước tổ chức dự án FastAPIRepo
-
RFC 9457 — Problem DetailsChuẩn định dạng lỗi APISpec
✅ Tự đánh giá hoàn thành
- Router theo tính năng, service không phụ thuộc HTTP
- Schema vào/ra riêng, không trả ORM object trực tiếp
- Một định dạng lỗi, đúng status code
- Dùng đúng def vs async def