Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Remove FastAPI's Default 422 Response Documentation

Tech May 7 3

Two modifications are required: one for the Swagger documentation and another for the built-in parameter validation error handler.

  1. 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)
  1. 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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.