Custom 404 Page
NotesCurrently, if you attempt to access a route that does not exist you get a JSON response displayed in the browser, for example:
{"detail":"Not Found"}That’s right for the APIs, but visitors to the website should see a proper page. Add a new template that will render a styled 404 not found error:
web/templates/404.htmljinja
{% extends "_base.html" %}
{% block content %}
<!-- Page Header -->
<header class="intro-header" style="background-image: url('/static/img/about-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Oops</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>404 Page not found.</p>
</div>
</div>
</div>
{% endblock %}Then, in main.py, add an exception handler. FastAPI calls it whenever an HTTPException is raised, whether by FastAPI itself for an unknown route, or by your own code, such as the 404 raised by get_blogpost_by_id_api:
main.pypython
from fastapi.exception_handlers import http_exception_handler # NEW
from fastapi.templating import Jinja2Templates # NEW
from starlette.exceptions import HTTPException as StarletteHTTPException # NEWmain.pypython
templates = Jinja2Templates('web/templates') # NEWmain.pypython
# Custom 404 page for the website; APIs keep their JSON errors
@main_app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code != 404 or request.url.path.startswith(settings.CONF_API_V1_STR):
return await http_exception_handler(request, exc)
return templates.TemplateResponse(request, "404.html", {"context": {"page": "404"}}, status_code=404)A few things to note:
- The handler is registered for Starlette’s
HTTPException, the base class of FastAPI’s. That way it also catches the “route not found” errors raised by Starlette itself. - Only 404s for the website get the HTML page. Anything else, and every error under
/api/v1, is passed to FastAPI’s defaulthttp_exception_handler, so the APIs still return meaningful JSON errors such as{"detail":"No blog post found with id ..."}. status_code=404matters. Without it, the “not found” page would be sent with200 OK, which tells search engines and monitoring that the page exists.
Now you’ll get the template rendered instead of the default JSON response:
Here is the complete main.py at the end of this section, including the Disable API Access changes covered shortly:
main.pypython
import time
import uvicorn
from fastapi import FastAPI, Request
from fastapi.exception_handlers import http_exception_handler
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException as StarletteHTTPException
from api import health_api, blog_apis
from config.settings import settings
from web.views import home_view, blog_views
# Swagger UI and the OpenAPI schema are only published when the APIs are enabled
main_app = FastAPI(openapi_url="/openapi.json" if settings.CONF_ENABLE_APIS else None)
templates = Jinja2Templates('web/templates')
# CORS
origins = [
"http://localhost:8000",
"https://localhost:8000",
"https://www.exampleforyou.net:8000",
"https://www.exampleforyou.net",
]
main_app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Process-Time", "X-Health-Check"],
)
# Middleware
@main_app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
# Custom 404 page for the website; APIs keep their JSON errors
@main_app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code != 404 or request.url.path.startswith(settings.CONF_API_V1_STR):
return await http_exception_handler(request, exc)
return templates.TemplateResponse(request, "404.html", {"context": {"page": "404"}}, status_code=404)
def configure():
configure_routing()
def configure_routing():
main_app.mount('/static', StaticFiles(directory='web/static'), name='static')
main_app.mount(settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH.rstrip('/'),
StaticFiles(directory=settings.CONF_IMAGE_UPLOADS_FILE_PATH, check_dir=False),
name='uploads')
main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])
if settings.CONF_ENABLE_APIS:
main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"])
main_app.include_router(home_view.router, tags=["web_views"])
main_app.include_router(blog_views.router, tags=["web_views"])
if __name__ == '__main__':
configure()
uvicorn.run(main_app,
host=settings.CONF_MAIN_APP_HOST,
port=settings.CONF_MAIN_APP_PORT,
log_level=settings.CONF_DEBUG_LEVEL,
ssl_keyfile=settings.CONF_SSL_KEYFILE,
ssl_certfile=settings.CONF_SSL_CERTFILE)
else:
configure()