Pydantic Schemas¶
Schema là gì?¶
Pydantic schemas validate dữ liệu đầu vào/đầu ra của API. Mọi request body và response đều đi qua schema → đảm bảo data luôn đúng format.
Schemas hiện tại¶
CourseCreate — Tạo khóa học¶
CourseResponse — Response trả về¶
class CourseResponse(BaseModel):
id: int
title: str
slug: str
content_html: Optional[str] = None
thumbnail_key: Optional[str] = None
thumbnail_url: Optional[str] = None # Set ở API layer
class Config:
from_attributes = True # Cho phép convert từ SQLAlchemy model
from_attributes = True
Cho phép CourseResponse.model_validate(db_course) — convert trực tiếp từ SQLAlchemy object sang Pydantic model.
UploadUrlRequest — Yêu cầu upload URL¶
class UploadUrlRequest(BaseModel):
file_name: str = "image.jpg" # Tên file (có default)
content_type: str = "image/jpeg" # MIME type (có default)
SignUploadUrlResponse — Response upload URL¶
class SignUploadUrlResponse(BaseModel):
upload_url: str # Presigned URL để PUT file
file_key: str # Key lưu trên R2
FinalizeUploadRequest — Xác nhận upload¶
Pattern khi tạo Schema mới¶
from pydantic import BaseModel, Field, EmailStr
from typing import Optional
# Schema cho CREATE (input)
class UserCreate(BaseModel):
name: str = Field(..., min_length=2, max_length=100)
email: EmailStr
phone: Optional[str] = None
# Schema cho RESPONSE (output)
class UserResponse(BaseModel):
id: int
name: str
email: str
class Config:
from_attributes = True
# Schema cho UPDATE (input) — tất cả fields optional
class UserUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=2, max_length=100)
email: Optional[EmailStr] = None
Naming Convention
XxxCreate— cho POST request bodyXxxResponse— cho responseXxxUpdate— cho PUT/PATCH request bodyXxxRequest— cho request body khác (upload, filter...)