Created
March 1, 2025 08:55
-
-
Save wwdegroot/7285cfcec169321b3a054b47f4013013 to your computer and use it in GitHub Desktop.
FastApi proxy endpoint
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
# adapted from https://github.com/fastapi/fastapi/issues/1788 | |
from fastapi import FastAPI | |
from starlette.requests import Request | |
from starlette.responses import StreamingResponse | |
from starlette.background import BackgroundTask | |
import uvicorn | |
import httpx | |
API_KEY = os.getenv('API_KEY') | |
app = FastAPI() | |
client = httpx.AsyncClient(base_url="https://base_url") | |
async def _reverse_proxy(request: Request): | |
# add extra query params | |
query_params = f"{request.url.query}&apikey={API_KEY}".encode("utf-8") | |
# edit headers here | |
headers = request.headers.mutablecopy() | |
url = httpx.URL( | |
path=request.url.path.replace("/proxy", ""), | |
query=query_params, | |
) | |
rp_req = client.build_request( | |
request.method, | |
url, | |
headers=headers.raw, | |
content=request.stream() | |
) | |
rp_resp = await client.send(rp_req, stream=True) | |
return StreamingResponse( | |
rp_resp.aiter_raw(), | |
status_code=rp_resp.status_code, | |
headers=rp_resp.headers, | |
background=BackgroundTask(rp_resp.aclose), | |
) | |
app.add_route( | |
"/proxy/{path:path}", | |
_reverse_proxy, | |
["GET", "POST"] | |
) | |
if __name__ == "__main__": | |
uvicorn.run(app, host="127.0.0.1", port=8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment