Hello I would like to know how to override the function that manages non-existing route, I can't find anything on the internet or I don't understand at all how to do it because I've tried everything I think.
If someone can help me to change the message
{
"detail": "Not Found"
}
when you try to contact the server with a bad route or / and method
Thank you very much.
Best regards,
Exactly, you can override the default HTTPException with Starlette's HTTPException
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse({"message":"endpoint not found" })
Now when i send a request to undefined endpoint, i 'll see this
INFO: 127.0.0.1:48818 - "GET /not_defined_endpoint HTTP/1.1" 200 OK
Out: "message":"endpoint not found"
If you want to include the default details you can do this:
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.encoders import jsonable_encoder
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse({"detail:":jsonable_encoder(exc), "message":"endpoint not found" })
Now you can see the default exceptions are included too.
INFO: 127.0.0.1:48844 - "GET /not_defined_endpoint HTTP/1.1" 200 OK
,Out: {"detail:":{"status_code":404,"detail":"Not Found"},"message":"endpoint not found"}
Hello, thank you very much
everything works great, I took the example in the doc with UnicornException...
You are welcome, glad it helped also thanks for closing the issue 馃殌
Thanks for the help here @ycd ! :clap: :bow:
Thanks for reporting back and closing the issue @Misteur54 :+1:
Most helpful comment
Hello, thank you very much
everything works great, I took the example in the doc with UnicornException...