6

文档建议使用客户端错误引发 HTTPException,这很好。但是如何在遵循 HTTPException 模型的文档中显示这些特定错误?意思是带有“详细信息”键的字典。

以下内容不起作用,因为 HTTPException 不是 Pydantic 模型。

@app.get(
    '/test', 
    responses={
        409 : {
            'model' : HTTPException, 
            'description': 'This endpoint always raises an error'
        }
    }
)
def raises_error():
    raise HTTPException(409, detail='Error raised')
4

1 回答 1

12

是的,它不是有效的 Pydantic 类型,但是由于您可以创建自己的模型,因此很容易为它创建模型。

from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from pydantic import BaseModel


class Dummy(BaseModel):
    name: str


class HTTPError(BaseModel):
    detail: str

    class Config:
        schema_extra = {
            "example": {"detail": "HTTPException raised."},
        }


app = FastAPI()


@app.get(
    "/test",
    responses={
        200: {"model": Dummy},
        409: {
            "model": HTTPError,
            "description": "This endpoint always raises an error",
        },
    },
)
def raises_error():
    raise HTTPException(409, detail="Error raised")

我相信这是你所期待的

在此处输入图像描述

于 2020-10-23T19:09:30.407 回答