你可以简单地
raise
HTTPException
而不是针对给定的响应模型返回不合适的响应,例如:
from fastapi import HTTPException
...
raise HTTPException(status_code=400, detail="Example bad request.")
编辑:
出于文档的目的,您可以执行以下操作以使其正确显示:
@example_router.post(
"/example",
response_model=schemas.Example,
status_code=201,
responses={200: {"model": schemas.Example}, 400: {"model": schemas.HTTPError}},
)
def create_example(...) -> models.Example:
...
raise HTTPException(status_code=400, detail="Example bad request.")
HTTPError
架构如下所示:
from pydantic import BaseModel
class HTTPError(BaseModel):
"""
HTTP error schema to be used when an `HTTPException` is thrown.
"""
detail: str