Search code examples
pythonfastapistarlette

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

Solution

  • 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