HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

05-让 FastAPI 接口更专业:文档契约、response_model 和模型组织

第 7 / 24 段:响应侧:`response_model` 是文档的基础

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Pydantic、OpenAPI

响应侧:response_model 是文档的基础(续)

# posts/router.py
from pydantic import BaseModel, Field

# 这个小模型只在发布接口用,不需要进 schemas.py
class PublishResult(BaseModel):
    post_id: int = Field(description="文章 ID")
    published_at: datetime = Field(description="发布时间")
    url: str = Field(description="访问 URL")

@router.post("/{post_id}/publish", response_model=PublishResult)
async def publish_post(post_id: int):
    post = await posts_repo.get(post_id)
    if not post:
        raise HTTPException(status_code=404)

    post.status = "published"
    post.published_at = datetime.now()
    await posts_repo.save(post)

    return {
        "post_id": post.id,
        "published_at": post.published_at,
        "url": f"/posts/{post.id}",
    }

对比:模型复用时就应该进 schemas.py