FastAPI 自定义错误处理中断了自动文档

FastAPI Custom Error Handling Broke Automatic Documentation

为了我们的需求,我做了如下修改

我的问题

My FastAPI 生成的自动文档仍显示默认错误代码和错误消息格式。

我的问题

是否可以更新 API 文档以反映我的更改,例如正确的错误代码和正确的错误输出格式?

目前的做法是修改生成的 OpenAPI https://fastapi.tiangolo.com/advanced/extending-openapi/

Currently there is no simple way. You have to modify the OpenAPI file as described here。这意味着您必须加载字典并删除对错误 422 的引用。这是一个最小的示例:

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.exceptions import RequestValidationError

app = FastAPI()


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    """Your custom validation exception."""
    message = 
    return JSONResponse(
        status_code=400,
        content={"message": f"Validation error: {exc}"}
    )


def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi()

    # look for the error 422 and removes it
    for method in openapi_schema["paths"]:
        try:
            del openapi_schema["paths"][method]["post"]["responses"]["422"]
        except KeyError:
            pass

    app.openapi_schema = openapi_schema
    return app.openapi_schema


app.openapi = custom_openapi