Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

We can achieve that by using FastAPI's exception_handler:

If you are in a hurry, you can use this:

from fastapi.responses import RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
    return RedirectResponse("/")

But more spesific approach, you can create your own Exception Handler(s):

class UberSuperHandler(StarletteHTTPException):
    pass
    
def function_for_uber_super_handler(request, exc):
    return RedirectResponse("/")


app.add_exception_handler(UberSuperHandler, function_for_uber_super_handler)
over 4 years ago · Santiago Trujillo Denunciar

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

I uses this method,

from fastapi.responses import RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")

@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
    return templates.TemplateResponse("404.html", {"request": request})
  • Make sure you have static folder, for your static files and templates folder your html files.
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda