File size: 1,094 Bytes
4c57e3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from fastapi import FastAPI, Request, Response
import httpx
import os

app = FastAPI()

BACKEND_URL = os.environ.get("BACKEND_URL")
AUTH_HEADER = os.environ.get("AUTH_HEADER")

@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
async def proxy(full_path: str, request: Request):
    # Monta URL destino
    url = f"{BACKEND_URL}/{full_path}"

    # Copia headers originais e adiciona Authorization
    headers = dict(request.headers)
    headers["Authorization"] = AUTH_HEADER

    # Lê corpo da requisição
    body = await request.body()

    # Faz requisição ao backend
    async with httpx.AsyncClient() as client:
        resp = await client.request(
            method=request.method,
            url=url,
            headers=headers,
            content=body,
            params=dict(request.query_params)
        )

    # Retorna resposta do backend
    return Response(
        content=resp.content,
        status_code=resp.status_code,
        headers=dict(resp.headers)
    )

# Para rodar:
# uvicorn proxy:app --reload --port 8000