fastapi (starlette) RedirectResponse redirect to post instead get method

When you want to redirect to a GET after a POST, the best practice is to redirect with a 303 status code, so just update your code to:

    # ...
    return RedirectResponse(redirect_url, status_code=303)

As you’ve noticed, redirecting with 307 keeps the HTTP method and body.

Fully working example:

from fastapi import FastAPI, APIRouter, Request
from fastapi.responses import RedirectResponse, HTMLResponse


router = APIRouter()

@router.get('/form')
def form():
    return HTMLResponse("""
    <html>
    <form action="/event/create" method="POST">
    <button>Send request</button>
    </form>
    </html>
    """)

@router.post('/create')
async def event_create(
        request: Request
):
    event = {"id": 123}
    redirect_url = request.url_for('get_event', **{'pk': event['id']})
    return RedirectResponse(redirect_url, status_code=303)


@router.get('/{pk}')
async def get_event(
        request: Request,
        pk: int,
):
    return f'<html>oi pk={pk}</html>'

app = FastAPI(title="Test API")

app.include_router(router, prefix="/event")

To run, install pip install fastapi uvicorn and run with:

uvicorn --reload --host 0.0.0.0 --port 3000 example:app

Then, point your browser to: http://localhost:3000/event/form

Leave a Comment