FastAPI by Example: Redirect Response
Redirecting users to a different URL is a standard web pattern. This sample code shows how to use `RedirectResponse` to perform temporary or permanent redirects.
Code
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/fastapi")
async def read_fastapi():
# Default is 307 Temporary Redirect
return RedirectResponse("https://fastapi.tiangolo.com")
@app.get("/pydantic")
async def read_pydantic():
# 301 Moved Permanently
return RedirectResponse(
"https://docs.pydantic.dev",
status_code=301
)
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id == "legacy":
# Redirect internal path
return RedirectResponse(url="/items/new-legacy")
return {"item_id": item_id}Explanation
RedirectResponse is a specialized response class that instructs the client to navigate to a different URL. It achieves this by returning an HTTP status code in the 3xx range and setting the Location header to the new destination. This mechanism is fundamental for handling resource movements, URL normalization, and post-login navigation flows. The most common redirect status codes are:
- 307 Temporary Redirect: (Default) Preserves the HTTP method (e.g., POST stays POST).
- 308 Permanent Redirect: Preserves the HTTP method.
- 303 See Other: Changes method to GET.
- 301 Moved Permanently: Traditional permanent redirect. May change method to GET.
Choosing the correct status code is crucial for both user experience and SEO. By default, FastAPI uses status code 307 (Temporary Redirect), which tells the browser to retry the request at the new location using the same HTTP method (e.g., a POST remains a POST). If you are permanently moving a resource, you should explicitly set the status code to 301 (Moved Permanently), which signals search engines to update their indices.
Redirects can point to either external URLs or internal application paths. External redirects are typically used to send users to documentation, partner sites, or authentication providers. Internal redirects, specified with a relative path (e.g., /items/new), are commonly used to maintain backward compatibility when refactoring API routes or to canonicalize URL structures.
Code Breakdown
RedirectResponse("...") creates a response with the Location header set to the provided URL.status_code=301 indicates a permanent move. Browsers and search engines will cache this redirect.url="/items/new-legacy" is a relative URL. The browser resolves this against the current domain.
