fastapi 移除自带的422响应文档

需要修改两部分,一是swagger文档,二是内置的参数校验失败处理函数。

1.移除swagger中的422响应描述

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


def openapi_patch_wrapper(app: FastAPI):

    def openapi_patch():
        if not app.openapi_schema:
            app.openapi_schema = get_openapi(
                title=app.title,
                version=app.version,
                openapi_version=app.openapi_version,
                description=app.description,
                terms_of_service=app.terms_of_service,
                contact=app.contact,
                license_info=app.license_info,
                routes=app.routes,
                tags=app.openapi_tags,
                servers=app.servers,
            )
            for _, method_item in app.openapi_schema.get("paths", dict()).items():
                for _, param in method_item.items():
                    responses = param.get("responses")
                    # remove 422 response, also can remove other status code
                    if "422" in responses:
                        del responses["422"]
        return app.openapi_schema

    return openapi_patch


app = FastAPI()
app.openapi = openapi_patch_wrapper(app)

2.自定义参数校验错误响应函数

"""
自定义fastapi参数校验失败的响应
"""

import json

from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import FastAPI


async def validation_exception_handler(
    request: Request,
    exc: RequestValidationError,
) -> JSONResponse:
    # 错误类型映射
    error_type_map = {
        "int_parsing": "整数格式错误",
        "string_too_short": "字符串长度不足",
        "string_too_long": "字符串长度超出限制",
        "value_error": "数值错误",
        "missing": "缺少必填参数",
    }

    errors = []
    for error in exc.errors():
        field_path = ".".join(str(loc) for loc in error["loc"])
        error_type = error["type"]
        message = error_type_map.get(error_type, error["msg"])

        errors.append(
            {"field": field_path, "message": message, "input": error["input"]}
        )

    return JSONResponse(
        status_code=400,
        content={
            "detail": f"参数校验错误,错误信息为:{json.dumps(errors,ensure_ascii=False)}"
        },
    )


app = FastAPI()
# 注册自定义参数校验失败处理函数
_ = app.exception_handler(RequestValidationError)(validation_exception_handler)

两个都用上,可以彻底去除框架自带的422响应。

posted @ 2023-10-13 09:20  CJTARRR  阅读(163)  评论(0)    收藏  举报