0
0
FastapiHow-ToBeginner · 3 min read

How to Redirect in FastAPI: Simple Guide with Examples

In FastAPI, you can redirect a client to another URL by returning a RedirectResponse from fastapi.responses. Use RedirectResponse(url="target_url") inside your path operation function to send a redirect response.
📐

Syntax

To redirect in FastAPI, import RedirectResponse from fastapi.responses. Then return RedirectResponse with the target URL as the url parameter.

  • RedirectResponse(url="target_url"): Creates a redirect response to the given URL.
  • The default HTTP status code is 307 (Temporary Redirect), but you can specify others like 301 (Permanent Redirect) using the status_code parameter.
python
from fastapi.responses import RedirectResponse

# Redirect to another URL
return RedirectResponse(url="/new-path", status_code=307)
💻

Example

This example shows a FastAPI app with a root path that redirects the user to the /welcome path using RedirectResponse. When you visit /, the browser will be redirected to /welcome.

python
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()

@app.get("/")
async def root_redirect():
    return RedirectResponse(url="/welcome")

@app.get("/welcome")
async def welcome():
    return {"message": "Welcome to the redirected page!"}
Output
Visiting '/' redirects to '/welcome' and shows JSON: {"message": "Welcome to the redirected page!"}
⚠️

Common Pitfalls

  • Forgetting to import RedirectResponse causes errors.
  • Not returning the RedirectResponse object (e.g., just calling it without return) means no redirect happens.
  • Using the wrong status code can confuse browsers; 307 is recommended for temporary redirects.
  • Redirecting to external URLs requires full URLs starting with http:// or https://.
python
from fastapi.responses import RedirectResponse

# Wrong: missing return
@app.get("/wrong")
async def wrong_redirect():
    RedirectResponse(url="/welcome")  # This does NOT redirect

# Correct:
@app.get("/correct")
async def correct_redirect():
    return RedirectResponse(url="/welcome")
📊

Quick Reference

ActionCode ExampleNotes
Redirect to internal pathreturn RedirectResponse(url="/path")Default status code 307 (temporary)
Redirect with permanent statusreturn RedirectResponse(url="/path", status_code=301)301 means permanent redirect
Redirect to external URLreturn RedirectResponse(url="https://example.com")Use full URL with scheme
Forget to return redirectRedirectResponse(url="/path")No redirect happens without return

Key Takeaways

Use RedirectResponse from fastapi.responses to perform redirects.
Always return RedirectResponse from your path operation function.
Default redirect status code is 307; specify status_code for others like 301.
Redirect URLs can be internal paths or full external URLs.
Common mistake: forgetting to return the RedirectResponse object.