Hide "input" from response upon 422 Validation Error #10352
-
First Check
Commit to Help
Example Codefrom fastapi import Body, FastAPI
from fastapi.security import HTTPBasicCredentials
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/login")
async def login(credentials: HTTPBasicCredentials = Body(...)):
return JSONResponse(content={'username': credentials.username})DescriptionThe example code is a simplified version of the basic auth I am trying to implement. I am sending "username" and "password" in request body. If either of the fields are missing from the request body, I get the following detailed response because obviously the HTTPBasicCredentials pydantic model has only two fields. I used "user" instead of "username" in the request body I want to hide the Operating SystemWindows Operating System DetailsNo response FastAPI Version0.103.1 Pydantic Version2.4.0 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
|
Same here, but for the |
Beta Was this translation helpful? Give feedback.
-
|
fastapi allows you to override request validation exceptions. One sort of solution to this is to override the exception with a modified version of the default fastapi request validation exception handler and exclude the input/url field from the response i.e. : @app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
print(exc.errors())
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": jsonable_encoder(exc.errors(), exclude={"input"})})The downside of this method would be that this removes the input/url field from all exception responses, unless theres a way to override the response exception handler for a single method. |
Beta Was this translation helpful? Give feedback.
-
|
I share another approach that proposes enabling/disabling both |
Beta Was this translation helpful? Give feedback.
fastapi allows you to override request validation exceptions. One sort of solution to this is to override the exception with a modified version of the default fastapi request validation exception handler and exclude the input/url field from the response i.e. :
The downside of this method would be that this removes the input/url field from all exception…