How to setup a simple proxy server using fastapi


Following code shows how to set up a simple proxy server using fastapi.

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
import httpx
import uvicorn

app = FastAPI()

@app.get("/{path:path}")
async def proxy(request: Request, path: str, scheme: str = "http"):
url = f"{scheme}://{path}"
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=request.headers, params=request.query_params)
return HTMLResponse(content=response.text, status_code=response.status_code)

def main():
uvicorn.run("app:app", host="0.0.0.0", port=8000, log_level="info")

if __name__ == "__main__":
main()

Put that code into a python file, such as app.py, launch the app on your server, for example, if locally just do:

python app.py

Once the fastapi is turned on, one can browse websites like this:

http://localhost:8000/bing.com?scheme=https

However, Notice that, this basic example will not work correctly for websites like google.com, as it does not handle cookies, JavaScript, and other dynamic content. Implementing a full-featured proxy server that can handle such websites is beyond the scope of a simple answer, but you can explore existing proxy server projects like mitmproxy or Tinyproxy for inspiration and guidance.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC