how does fastapi use httpexception in response?

Yes it is not a valid Pydantic type however since you can create your own models, it is easy to create a Model for it.

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")

I believe this is what you are expecting

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top