Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI - How to use HTTPException in responses?

The documentation suggests raising an HTTPException with client errors, which is great. But how can I show those specific errors in the documentation following HTTPException's model? Meaning a dict with the "detail" key.

The following does not work because HTTPException is not a Pydantic model.

@app.get(
    '/test', 
    responses={
        409 : {
            'model' : HTTPException, 
            'description': 'This endpoint always raises an error'
        }
    }
)
def raises_error():
    raise HTTPException(409, detail='Error raised')
like image 206
Mojimi Avatar asked Oct 23 '20 13:10

Mojimi


1 Answers

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

like image 170
Yagiz Degirmenci Avatar answered Sep 21 '22 15:09

Yagiz Degirmenci