URL redirection in the HTTP protocol is basically a header, i.e., the Location
response header, indicating the URL to redirect a page to (see here and here for more details). That being said, it does not prevent one to provide a body in the redirect response as well. Since FastAPI/Starlette's RedirectResponse
does not provide the relevant content
parameter, which would allow you to define the response body, you could instead return a custom Response
directly with a 3xx
(redirection) status code and the Location
header holding the URL to redirect to. If you want the redirected request to reuse the method (e.g., POST
) and the body of the original request, then you could use 307 Temporary Redirect
status response code (the relevant Starlette implementation of all status
codes can be found here).
Working Example:
app.py
from fastapi import FastAPI, Request, Response, Form, status
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
@app.post('/submitFinal')
def final(msg: str = Form(...)):
return f'You reached your destination. The msg is {msg}'
@app.post('/submit')
def redirect(msg: str = Form(...)):
headers = {'Location': '/submitFinal'}
return Response(content=msg, headers=headers, status_code=status.HTTP_307_TEMPORARY_REDIRECT)
@app.get('/')
def index(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault() // Cancel the default action
var formElement = document.getElementById('myForm');
var data = new FormData(formElement);
fetch('/submit', {
method: 'POST',
body: data
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("responseArea").innerHTML = data;
})
.catch(error => {
console.error(error);
});
});
});
</script>
</head>
<body>
<h1>Send a message</h1>
<form id="myForm">
Message : <input type="text" name="msg" value="foo">
<input class="submit" type="submit" value="Submit">
</form>
<div id="responseArea"></div>
</body>
</html>