Remove FastAPI's Default 422 Response Documentation
Two modifications are required: one for the Swagger documentation and another for the built-in parameter validation error handler.
- Remove the 422 response description from Swagger
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)
- Create a custom praameter validasion error response function
"""
Custom response for FastAPI parameter validation errors
"""
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 mapping
error_type_map = {
"int_parsing": "Integer format error",
"string_too_short": "String is too short",
"string_too_long": "String is too long",
"value_error": "Value error",
"missing": "Missing required parameter",
}
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"Parameter validation error, error details: {json.dumps(errors,ensure_ascii=False)}"
},
)
app = FastAPI()
# Register custom parameter validation error handler
_ = app.exception_handler(RequestValidationError)(validation_exception_handler)
Using botth methods ensures the framework's default 422 response is fully removed.