How to Handle 404 Errors in FastAPI: Simple Guide
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.
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
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.
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} )
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.