Fastapi: Can fastapi proxy another site as a response to the request?

Created on 25 Jul 2020  ·  5Comments  ·  Source: tiangolo/fastapi

This may be a silly question. Can fastapi proxy another site as a response to the request?

I did some research. All pages I found are Nginx reverse proxy fastapi. I already did that to solve the SSL problem.

My system workflow:

image

RedirectResponse is a rewrite, not a proxy.
Static Files are for local files.
HTMLResponse is for static HTML.

Can you give me some tips on how to proxy another site in fastapi? Thank you.

question

Most helpful comment

@eelkeh @thomas-maschler I just ran into this myself and found it was covered in the docs here referencing accessing a file system. A proxy should resolve the path same way.

from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

so my proxy use case will look like:

@app.get(“/tiles/{path:path}”)
async def tile_request(path: str, response: Response):
    async with httpx.AsyncClient() as client:
        proxy = await client.get(f“http://containername:7800/{path}”)
    response.body = proxy.content
    response.status_code = proxy.status_code
    return response

All 5 comments

I have the same issue! Did you find a solution?

This is not quite working but it might be a start?

from fastapi import FastAPI, Response
import requests

app = FastAPI()

def _proxy(*args, **kwargs):
    t_resp = requests.request(
        method="GET",
        url="https://google.com/",
        allow_redirects=False)

    response = Response(content=t_resp.contents, status_code=t_resp.status_code)
    return response

@app.get("/")
def proxy():
    return _proxy()

How would I allow any path to be resolved by the proxy ? With flask you can do something like this

from flask import Flask
from requests import get

app = Flask('__main__')
SITE_NAME = 'https://google.com/'

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def proxy(path):
  return get(f'{SITE_NAME}{path}').content

app.run(host='0.0.0.0', port=8080)

Can I allow wildcard paths with fastAPI ?

Any change that anyone made progress with this? I'm still looking for a solution

@eelkeh @thomas-maschler I just ran into this myself and found it was covered in the docs here referencing accessing a file system. A proxy should resolve the path same way.

from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}

so my proxy use case will look like:

@app.get(“/tiles/{path:path}”)
async def tile_request(path: str, response: Response):
    async with httpx.AsyncClient() as client:
        proxy = await client.get(f“http://containername:7800/{path}”)
    response.body = proxy.content
    response.status_code = proxy.status_code
    return response
Was this page helpful?
0 / 5 - 0 ratings