如何为 HTTP 400 错误定义单独的 response_model?

How to define a separate response_model for HTTP 400 errors?

我不得不将 response_model 中的所有值设置为可选。

class ConnectOut(BaseModel):
    product_id: Optional[str]
    expires_at: Optional[datetime]
    detail: Optional[ErrorType]

如果我不这样做,下面的 HTTP400 路径将抛出验证错误,因为在出​​现 400 错误时将不会提供 product_id 和 expires_at。

@router_connect.post("/", status_code=200, response_model=ConnectOut)
async def connect(
    body: ConnectIn,
    response: Response,
):
    if account.is_banned:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return {"detail": ErrorType.USER_IS_BANNED}

有没有办法定义 response_model 表示成功,response_model 表示 400 条错误消息?

非常感谢,

您可以简单地 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