响应侧: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