python 覆盖FastAPI的HTTPException响应正文

93ze6v8z  于 2023-05-16  发布在  Python
关注(0)|答案(2)|浏览(106)

我目前正在fastAPI中为一个API编写一些端点。我正在定义扩展fastapi的HTTPException的类。
问题是HTTPException返回一个响应主体,其中包含一个名为detail的属性,该属性将是一个字符串或JSON结构,具体取决于您传递给它的对象,如下所示。

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

{   "detail": "error message here" }

我想覆盖这个行为,让它用我自己的结构来响应。
我知道我可以使用异常处理程序装饰器安装自定义异常,并使其返回JSONResponse对象,但这不是我要找的。

ljo96ir5

ljo96ir51#

一个选项是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中找到。

nx7onnlm

nx7onnlm2#

建议使用FastAPI提供的状态模块,而不是直接使用数字HTTP状态代码。这种方法提高了代码的可读性并降低了出错的可能性。

from fastapi import FastAPI, Response, status

    myapp = FastAPI()

    @myapp.get("/")
    async def app_func(response: Response, myparam: str):
        valid_params = ['a', 'b', 'c']

        if myparam not in valid_params:
            response.status_code = status.HTTP_400_BAD_REQUEST
            return {
                'message': 'Invalid parameter.',
                'detail': f"The provided parameter '{myparam}' is not valid. Valid parameters are: a, b, c"
            }

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

相关问题