覆盖 fastAPI 的 HTTPException 响应主体

问题描述

我目前正在为 fastAPI 中的 API 编写一些端点。 我正在定义扩展 fastapi 的 HTTPException 的类。

问题是 HTTPException 返回一个响应主体,其中包含一个名为 detail 的属性,它可以是字符串或 json 结构,具体取决于您传递给它的对象,如下所示。

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


{   "detail": "error message here" }

我想覆盖此行为并让它以我自己的结构响应。

我知道我可以使用异常处理程序装饰器安装自定义异常并让它返回一个 JSONResponse 对象,但这不是我想要的。

解决方法

一种选择是 set the status code 对应您的异常,然后返回自定义响应正文。

这是一个简单的玩具示例,使用这种方法来解决手头的问题:

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!'}      

可以在 here 中找到可用状态代码的完整列表。