Skip to content

Custom exception handling not updating OpenAPI status code #2455

@conradogarciaberrotaran

Description

@conradogarciaberrotaran

Hi, I'm trying to override the 422 status code to a 400 across every endpoint on my app, but it keeps showing as 422 on the openapi docs.

Description

This is how i override the 422.

from fastapi import FastAPI, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

app = FastAPI()

app.include_router(my_router, prefix="/log")


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    """
    Overrides FastAPI default status code for validation errors
    from 422 to 400
    """
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

It returns 400 successfully but, the OpenAPI shows:
image

What's the correct way to override the 422 and update the OpenAPI docs schema?
Thank you

Environment

  • OS: Linux
  • FastAPI Version: 0.61.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions