【问题标题】:FastAPI - How to use HTTPException in responses?FastAPI - 如何在响应中使用 HTTPException?
【发布时间】:2021-02-06 14:08:12
【问题描述】:

文档建议使用客户端错误引发 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')

【问题讨论】:

  • example 不会这样做吗?如果没有,你能告诉我们它在 swagger 文档中的样子吗?

标签: python fastapi starlette


【解决方案1】:

是的,它不是有效的 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")

我相信这是你所期待的

【讨论】:

  • 感谢您,我想知道为什么我无法在 swagger 文档中显示错误。我看到您需要添加responses: arg。
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 2020-11-03
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多