【问题标题】:Displaying of FastAPI validation errors to end users向最终用户显示 FastAPI 验证错误
【发布时间】:2019-10-31 11:36:38
【问题描述】:

我正在寻找一些将 FastAPI 验证消息格式化为人类可读格式的库或代码示例。例如。这个端点:

@app.get("/")
async def hello(name: str):
    return {"hello": name}

如果我们错过了name查询参数,将产生下一个json输出:

{ 
    "detail":[ 
        { 
            "loc":[ 
                "query",
                "name"
            ],
            "msg":"field required",
            "type":"value_error.missing"
        }
    ]
}

所以我的问题是,如何:

  1. 将其转换为“需要名称字段”之类的内容(针对各种可能的错误)以显示在 toasts 中。
  2. 用它来显示表单验证消息
  3. 如果可能的话,从 api 描述中自己生成表单

【问题讨论】:

    标签: python swagger openapi fastapi


    【解决方案1】:

    FastAPI 具有出色的异常处理功能,因此您可以通过多种方式自定义异常。

    您可以引发 HTTPException,HTTPException 是一个普通的 Python 异常,带有与 API 相关的附加数据。但是你不能返回它你需要引发它,因为它是一个 Python 异常

    from fastapi import HTTPException
    ...
    @app.get("/")
    async def hello(name: str):
        if not name:
            raise HTTPException(status_code=404, detail="Name field is required")
        return {"Hello": name}
    

    通过将name: str 添加为查询参数,它会自动变为必需,因此您需要添加Optional

    from typing import Optional
    ...
    @app.get("/")
    async def hello(name: Optional[str] = None):
        error = {"Error": "Name field is required"}
        if name:
            return {"Hello": name}
        return error
    
    $ curl 127.0.0.1:8000/?name=imbolc
    {"Hello":"imbolc"}
    ...
    $ curl 127.0.0.1:8000
    {"Error":"Name field is required"}
    

    但在你的情况下,我认为这是处理 FastAPI 中的错误的最佳方法,覆盖 validation_exception_handler

    from fastapi import FastAPI, Request, status
    from fastapi.encoders import jsonable_encoder
    from fastapi.exceptions import RequestValidationError
    from fastapi.responses import JSONResponse
    ...
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content=jsonable_encoder({"detail": exc.errors(), "Error": "Name field is missing"}),
        )
    ...
    @app.get("/")
    async def hello(name: str):
        return {"hello": name}
    

    你会得到这样的回应:

    $ curl 127.0.0.1:8000
    
     {
       "detail":[
          {
             "loc":[
                "query",
                "name"
             ],
             "msg":"field required",
             "type":"value_error.missing"
          }
       ],
       "Error":"Name field is missing"
    }
    

    您可以自定义您的content,但如果您愿意:

    {
    "Error":"Name field is missing",
       "Customize":{
          "This":"content",
          "Also you can":"make it simpler"
       }
    }
    

    【讨论】:

    • 覆盖validation_exception_handler 并在其中硬编码错误消息不是一个好主意;基本上,您只能将其应用于 hello world 示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2019-08-25
    • 1970-01-01
    • 2012-10-06
    • 2023-04-09
    相关资源
    最近更新 更多