fastapi: Handling Exception Response format
Hello.
I want to change the validation error response and make it inside app object.
I’ve found this example:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
)
But can’t understand how to add this function to app object without decorator:
app = FastAPI(
title='Bla API',
description='Bla description',
APIRoute('/api', api.toggle, methods=['POST'],
description='Switch interface state',
response_description='Interface successfully switched',
response_class=JSONResponse,
response_model=api.Success,
responses={**api.post_responses},
),
...
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 20 (6 by maintainers)
@MacMacky Ok. Thanks again for your help.
may be you can try this:
And in main.py
If I understood the idea correctly this is how I should have done it:
GUI part:
Api part:
And my start point
It works perfectly! =)
But I still have a question regarding validator: I rewrote
exception_handler:and I have validation handling format I wanted:
But on Swagger page 422 status still has default schema:
How can I change it?
Why is the use of decorators problematic? Defininig pretty much anything inside the FastAPI constructor like that is certainly an uncommon way to do things and much of the discussion in #687 was about how that approach would be likely to be less ergonomic for routes when taking FastAPI’s goals into account (like how Path parameters would end up split between the route declaration and the function signature).
It’s not currently possible to do that with
exception_hadlerwith FastAPI right now (upstream Starlette versions support that, but it causes compatibility issues with FastAPI, see #683), but why do you want to do that with the exception handler?