Serializers & DTOs:控制 API 暴露的内容
发布: (2026年2月26日 GMT+8 03:48)
2 分钟阅读
原文: Dev.to
Source: Dev.to
什么是 DTO?
DTO(数据传输对象) 明确定义了向客户端暴露的具体数据,防止内部字段泄漏。
示例模型
考虑一个具有以下字段的 Item 模型:
idnamedescriptionpricecreated_atinternal_db_id← 敏感内部字段deleted_at← 敏感内部字段
如果不使用 DTO,这些字段都会返回给客户端。
DTO 定义
class ItemResponseDTO(BaseModel):
id: int
name: str
price: float
class Config:
from_attributes = True
该 DTO 只暴露 id、name 和 price。
在 FastAPI 端点中使用 DTO
@app.get("/items", response_model=List[ItemResponseDTO])
def get_all_items():
db = SessionLocal()
items = db.query(Item).all()
db.close()
return items
FastAPI 的 response_model 参数会根据 DTO 过滤输出。
- 不使用 DTO – 对
/items/full的请求会返回所有模型字段,包括internal_db_id和deleted_at。 - 使用 DTO – 对
/items的请求只返回ItemResponseDTO中定义的字段,从而隐藏敏感数据。
始终明确地定义你的 API 暴露了哪些内容。