0
0
FastapiDebug / FixBeginner · 3 min read

How to Handle 404 Errors in FastAPI: Simple Guide

In FastAPI, you handle 404 errors by creating an exception handler for starlette.exceptions.HTTPException with status code 404. Use the @app.exception_handler(404) decorator to define a custom response when a resource is not found.
🔍

Why This Happens

A 404 error occurs in FastAPI when a client requests a URL path that does not match any defined route. By default, FastAPI returns a generic 404 response without custom message or formatting.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

# No handler for other paths
Output
{ "detail": "Not Found" } # HTTP status code: 404
🔧

The Fix

To customize 404 errors, add an exception handler for HTTPException with status code 404. This lets you return a friendly message or custom JSON when a route is missing.

python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

@app.exception_handler(HTTPException)
async def not_found_handler(request: Request, exc: HTTPException):
    if exc.status_code == 404:
        return JSONResponse(
            status_code=404,
            content={"message": "Sorry, the resource you are looking for was not found."}
        )
    return JSONResponse(
        status_code=exc.status_code,
        content={"message": exc.detail}
    )
Output
{ "message": "Sorry, the resource you are looking for was not found." } # HTTP status code: 404
🛡️

Prevention

To avoid unexpected 404 errors, always define routes clearly and test your API paths. Use exception handlers to provide helpful feedback to users. Employ automated tests to catch missing routes early.

  • Keep route paths consistent and documented.
  • Use @app.exception_handler(404) to customize responses.
  • Write tests that check for valid and invalid URLs.
⚠️

Related Errors

Other common HTTP errors include 400 (Bad Request) and 500 (Internal Server Error). You can handle these similarly by creating exception handlers for their status codes to improve user experience.

Key Takeaways

Use @app.exception_handler(404) to catch and customize 404 errors in FastAPI.
A 404 error means the requested URL path does not match any route.
Return clear, user-friendly messages in your 404 handler to improve API usability.
Test your API routes to prevent unexpected 404 errors.
Handle other HTTP errors similarly for consistent error management.