response_model 参数声明端点响应的形状。FastAPI 使用它来验证、过滤和序列化返回的数据——并在 API 文档中记录响应。它最重要的作用:确保您只公开预期的字段(例如从不泄露密码)。
问题:泄露敏感字段
python
():
name:
email:
password:
() -> User:
db.get_user()
class UserOut(BaseModel): # the SAFE public shape — no password
name: str
email: str
@app.get("/users/{id}", response_model=UserOut)
def get_user(id: int):
return db.get_user(id) # returns a full user, but FastAPI FILTERS it to UserOut
# response → { "name": "...", "email": "..." } — password stripped automatically
使用 response_model=UserOut,FastAPI 会获取您返回的任何内容,并将其过滤到仅在 UserOut 中声明的字段——因此密码(以及任何其他额外字段)会从响应中删除,即使您返回了完整对象。
✓ FILTERS the output to only the declared fields (key for hiding sensitive data)
✓ VALIDATES that your response matches the declared schema (catches mistakes)
✓ SERIALIZES the data to JSON correctly
✓ DOCUMENTS the response shape in the OpenAPI/Swagger docs
@app.get("/users/{id}")
def get_user(id: int) -> UserOut: # the -> return type works like response_model
return db.get_user(id)
# response_model_exclude_unset=True → omit fields not explicitly set
response_model 对于安全性和清晰的 API 设计都很重要。
它最关键的作用是防止意外数据泄露——通过准确声明响应应包含的字段,FastAPI 会过滤掉所有其他内容(如密码哈希、内部标志或令牌),即使您的代码返回了完整的数据库对象,也能消除一个常见的严重漏洞。
除此之外,它根据声明的模式验证您的响应(捕捉返回错误形状的 bug),确保正确的序列化,并在自动生成的 API 文档中记录响应。
使用单独的输入和输出模型的模式(其中 response_model 控制公开的内容)是安全、定义明确的 API 的最佳实践,对于任何返回数据的端点,这都是重要的知识。