FastAPI-如何在响应中使用HTTPException?

问题描述

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

解决方法

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

我相信这就是您的期望

enter image description here