Last active
March 24, 2025 08:47
-
-
Save Calcifer777/9956fc936488a874c10b2c3bcbbf1839 to your computer and use it in GitHub Desktop.
fasatapi reverse proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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