Handling and Redirecting 404 Errors in FastAPI: A Guide
Problem: You're building a web application using FastAPI and you want to ensure that users get a clear and consistent experience when they encounter a 404 Not Found error. You desire a custom error page instead of the default FastAPI response, and maybe even a redirect to a different page.
Scenario:
Imagine you have a simple FastAPI application with an endpoint that returns a user's information based on their ID. If a user tries to access a non-existent ID, they receive the default FastAPI 404 response.
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Simulated user data
users = {1: {"name": "Alice", "email": "[email protected]"},
2: {"name": "Bob", "email": "[email protected]"}}
if user_id in users:
return users[user_id]
else:
raise HTTPException(status_code=404, detail="User not found")
This code raises an HTTPException
with a status code of 404, but the response is still the basic FastAPI error message. Let's enhance this for a better user experience.
Enhancing the 404 Experience
Custom Error Page:
We can create a custom 404 page using FastAPI's exception handling capabilities.
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
return HTMLResponse(
"""
<h1>Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
<a href="/">Go back to the homepage</a>
""",
status_code=404
)
else:
return exc
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# ... (rest of the code)
This code defines a custom exception handler for HTTPException
s. If the status code is 404, it returns a custom HTML response with a friendly message and a link to the homepage.
Redirecting to a Different Page:
We can also redirect users to a different page, such as a "404 Not Found" page, using the RedirectResponse
.
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
return RedirectResponse("/not-found", status_code=302)
else:
return exc
# ... (rest of the code)
@app.get("/not-found")
async def not_found():
return HTMLResponse(
"""
<h1>Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
"""
)
In this example, upon encountering a 404 error, the user will be redirected to the /not-found
endpoint which displays a custom 404 page.
Conclusion
By implementing these techniques, you can provide a more user-friendly and professional experience for users who encounter 404 errors in your FastAPI application. This enhances the usability and overall impression of your web application.
Remember: Always consider the specific requirements of your application and user expectations when designing your error handling strategy.
Further Exploration:
- FastAPI Error Handling: https://fastapi.tiangolo.com/tutorial/handling-errors/
- RedirectResponse: https://fastapi.tiangolo.com/tutorial/responses/
- HTTP Status Codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status