r/FastAPI • • Jan 19 '21

Question How to override default 404 route not found

Sorry this is probably a very noob question.

So I google and only found very few issues on this. But none of them answers how to catch only route not found. Both of the following links are saying how to catch all errors, if I understand correctly.

https://fastapi.tiangolo.com/tutorial/handling-errors/

https://stackoverflow.com/questions/62986778/fastapi-handling-and-redirecting-404

The doc doesn't even document how to override the default error message {"detail":"Not Found"} . Am I missing something?

I can of course catch all errors then handle them individually but it seems over-complicating things and this is a weird approach to solve this common issue.

I am actually using fastapi to build a small traditional HTML website - none of my route returns JSON.

I know it's of a misuse of the framework but I thought since it supports Template and HTML response so I just give it a try. Or should I just switch back to Flask?

5 Upvotes

8 comments sorted by

2

u/[deleted] Jan 19 '21
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

HTML_404_PAGE = "<h1>404</h1>"


async def not_found(request, exc):
    return HTMLResponse(content=HTML_404_PAGE, status_code=exc.status_code)


exceptions = {
    404: not_found,
}

app = FastAPI(exception_handlers=exceptions)


@app.get("/")
def homepage():
    return {"message": "hello there"}

1

u/pk028382 Jan 19 '21

This solution is quite clean.

But yet, it's still catching all 404 error.

I want to differentiate the "route not found" and "controller raising 404". Using your example, both cases will show both the 404 page.

It's good enough for my case so thanks!

2

u/[deleted] Jan 19 '21

Not the best solution, but if it works for you,

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse

HTML_404_PAGE = "<h1>404</h1>"


async def not_found(request: Request, exc: HTTPException):
    err_not_controller = True

    try:
        err_not_controller = exc.headers.get("404-error") != "controller"
    except AttributeError:
        pass

    if err_not_controller:
        return HTMLResponse(content=HTML_404_PAGE, status_code=exc.status_code)
    return JSONResponse({"detail": exc.detail})


exceptions = {
    404: not_found,
}

app = FastAPI(exception_handlers=exceptions)


@app.get("/{name}")
def homepage(request: Request, name: str):
    if name != "king":
        raise HTTPException(
            status_code=404,
            detail="not valid name",
            headers={"404-error": "controller"},
        )
    return name

1

u/backtickbot Jan 19 '21

Fixed formatting.

Hello, redwastheimposterr: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

4

u/[deleted] Jan 19 '21

When looking at the source for the FastAPI class you can see that it directly inherits from Starlette and accepts a parameter called "exception_handlers":

https://github.com/tiangolo/fastapi/blob/master/fastapi/applications.py

I have not tried this, but I guess you should be able to use code as described in the Starlette documentation to specify custom exception handlers:

https://www.starlette.io/exceptions/

1

u/Deadly_chef Jan 19 '21

There is a whole chapter in the tutorial on exception handling and overwriting the default handlers

1

u/AdStandard6548 Jul 09 '26

{"detail":"Rota não encontrada!"}