I am trying to write a middleware in my FastAPI application, so that requests coming to endpoints matching a particular format will be re-routed to a different URL, but I am unable to find a way to do that since request.url
is read-only.
I am also looking for a way to update request headers before re-routing.
Are these things even possible in FastAPI?
Redirection is the best I could do so far:
from fastapi import Request
from fastapi.responses import RedirectResponse
@app.middleware("http")
async def redirect_middleware(request: Request, call_next):
if matches_certain_format(request.url.path):
new_url = create_target_url(request.url.path)
return RedirectResponse(url=new_url)