0
0
FastapiHow-ToBeginner · 3 min read

How to Use RedirectResponse in FastAPI: Simple Guide

In FastAPI, use RedirectResponse from fastapi.responses to redirect a client to a different URL by returning it from a path operation. Simply create a RedirectResponse with the target URL and return it in your endpoint function.
📐

Syntax

The RedirectResponse is imported from fastapi.responses. You create it by passing the target URL as a string to its constructor. Then return this response from your path operation function.

Example parts:

  • RedirectResponse(url: str): The URL to redirect to.
  • Returned from the endpoint to send a redirect HTTP response.
python
from fastapi.responses import RedirectResponse

RedirectResponse(url="your-target-url")
💻

Example

This example shows a FastAPI app with a root endpoint that redirects the user to /new-location. When you visit /, the browser will be redirected to /new-location.

python
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()

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

@app.get("/new-location")
async def new_location():
    return {"message": "You have been redirected here!"}
Output
Visiting '/' redirects to '/new-location' which returns JSON: {"message": "You have been redirected here!"}
⚠️

Common Pitfalls

Common mistakes when using RedirectResponse include:

  • Not returning the RedirectResponse object from the endpoint, which means no redirect happens.
  • Using relative URLs incorrectly; always provide a valid URL path or full URL.
  • Forgetting that redirects send HTTP status code 307 by default, which preserves the HTTP method (GET, POST). Use status_code=302 if you want a temporary redirect with method change.
python
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()

# Wrong: Not returning RedirectResponse
@app.get("/wrong")
async def wrong_redirect():
    RedirectResponse(url="/new-location")  # This does nothing

# Right: Return RedirectResponse
@app.get("/right")
async def right_redirect():
    return RedirectResponse(url="/new-location", status_code=302)
📊

Quick Reference

FeatureDescription
RedirectResponse(url: str, status_code: int = 307)Creates a redirect response to the given URL with optional status code.
Default status code307 Temporary Redirect (preserves HTTP method)
Common status codes302 Found (temporary redirect), 301 Moved Permanently
UsageReturn RedirectResponse from FastAPI endpoint to redirect client
URLCan be relative path or full URL

Key Takeaways

Import and return RedirectResponse from fastapi.responses to redirect users.
Pass the target URL as a string to RedirectResponse's constructor.
Default redirect status is 307; use status_code=302 for common temporary redirects.
Always return the RedirectResponse object from your endpoint function.
URLs can be relative paths or full URLs depending on your redirect needs.