In FastAPI, when receiving the POST request from an HTML Form, you might need to get the URL of the page that triggered the POST request. Tracking the source of form submissions maybe required for some additional business logic in your handler.
In my specific case, I wanted to flash an error message when the user triggered a validation error and then redirect the user to the original page.
Your first instinct maybe to assume that such information is available directly via an attribute of the request object. You are on the right track. The technical term you're looking for is the Referrer URL and luckily this information is available in
request.headers. The HTTP Referrerheader can be used to identify the origin of a form submission in FastAPI.
For the sake of clarity and context, in FastAPI, you can use the
request object to access information about the incoming request, including the URL of the page from which the form was posted. The
request object is available in the function that handles the form submission, and you can use the
request.headers attribute to access the headers of the request. The headers will include the
Referer header, which specifies the URL of the page from which the form was submitted.
Here is an example of how you could access the
Referer header in a FastAPI application:
from fastapi import FastAPI, Request app = FastAPI() @app.post("/submit-form") def submit_form(request: Request): referer = request.headers.get("Referer") # do something with the referer URL
In this example, we use the
get() method of the
request.headers object to access the
Referer header, and then we can use the value of the
referer variable to do whatever we need to with the URL of the page from which the form was submitted.