Overriding fastAPI's HTTPException response body

Viewed 2705

I'm currently writing a few end points for an API in fastAPI. I'm defining classes that extend fastapi's HTTPException.

The problem is that HTTPException returns a response body with an attribute called detail which will either be a string or a json structure depending on what object you pass to it as seem below.

{
  "detail": {
    "msg": "error message here"
  }
}


{   "detail": "error message here" }

I would like to override this behavior and let it respond with my own structure.

I'm aware that i can install custom exceptions using the exception handler decorator and have that return a JSONResponse object but this is not what i'm looking for.

1 Answers

One option is to set the status code corresponding to your exception, and then return a custom response body.

Here is a simple toy example using this approach to workaround the issue at hand:

from fastapi import FastAPI, Response, status

myapp = FastAPI()

@myapp.get("/")
async def app_func(response: Response, myparam: str):

    #end point code here

    valid_params = ['a', 'b', 'c']
    
    if myparam not in valid_params:
        #Customize logic, status code, and returned dict as needed

        response.status_code = status.HTTP_400_BAD_REQUEST

        return {'message': 'Oh no! I failed (without detail key)'}

    
    response.status_code = status.HTTP_200_OK
    return {'message': 'Yay! I succeeded!'}      

A full list of available status codes can be found here.

Related