pythonhttp-status-code-404fastapi

FastAPI handling and redirecting 404


How can i redirect a request with FastAPI if there is a HTTPException?

In Flask we can achieve that like this:

@app.errorhandler(404)
def handle_404(e):
    if request.path.startswith('/api'):
        return render_template('my_api_404.html'), 404
    else:
        return redirect(url_for('index'))

Or in Django we can use django.shortcuts:

from django.shortcuts import redirect

def view_404(request, exception=None):
    return redirect('/')

How we can achieve that with FastAPI?


Solution

  • I know it's too late but this is the shortest approach to handle 404 exceptions in your personal way.

    Redirect

    from fastapi.responses import RedirectResponse
    
    
    @app.exception_handler(404)
    async def custom_404_handler(_, __):
        return RedirectResponse("/")
    

    Custom Jinja Template

    from fastapi.templating import Jinja2Templates
    from fastapi.staticfiles import StaticFiles
    
    templates = Jinja2Templates(directory="templates")
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    @app.exception_handler(404)
    async def custom_404_handler(request, __):
        return templates.TemplateResponse("404.html", {"request": request})
    

    Serve HTML from file

    @app.exception_handler(404)
    async def custom_404_handler(_, __):
        return FileResponse('./path/to/404.html')
    

    Serve HTML directly

    from fastapi.responses import HTMLResponse
    
    response_404 = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Not Found</title>
    </head>
    <body>
        <p>The file you requested was not found.</p>
    </body>
    </html>
    """
        
    @app.exception_handler(404)
    async def custom_404_handler(_, __):
        return HTMLResponse(response_404)
    

    Note: exception_handler decorator passes the current request and exception as arguments to the function. I've used _ and __ where the variables are unnecessary.