Skip to content

Instantly share code, notes, and snippets.

@Calcifer777
Last active March 24, 2025 08:47
Show Gist options
  • Save Calcifer777/9956fc936488a874c10b2c3bcbbf1839 to your computer and use it in GitHub Desktop.
Save Calcifer777/9956fc936488a874c10b2c3bcbbf1839 to your computer and use it in GitHub Desktop.
fasatapi reverse proxy
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from starlette.background import BackgroundTask
import httpx
app = FastAPI()
client = httpx.AsyncClient(base_url="http://localhost:8000/")
async def reverse_proxy(r: Request):
url = httpx.URL(
path=r.url.path,
query=r.url.query.encode("utf-8"),
)
fwd_r = client.build_request(
r.method,
url,
headers=r.headers.raw,
content=await r.body(),
)
response = await client.send(fwd_r, stream=True)
return StreamingResponse(
response.aiter_raw(),
status_code=response.status_code,
headers=response.headers,
background=BackgroundTask(response.aclose),
)
app.add_route("/{path:path}", reverse_proxy, methods=["GET", "POST"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment