Spaces:
Paused
Paused
File size: 4,328 Bytes
8f50400 3283add 8f50400 3283add 8f50400 3283add cb961d4 8f50400 3283add 8f50400 3283add 8f50400 3283add 8f50400 cb961d4 8f50400 cb961d4 8f50400 cb961d4 8f50400 3283add 8f50400 cb961d4 8f50400 cb961d4 8f50400 cb961d4 8f50400 3283add 8f50400 cb961d4 3283add bfb3375 8f50400 cb961d4 | 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | from fastapi import FastAPI, Depends, HTTPException, Request, Response
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from httpx import AsyncClient, Timeout
import os
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace with your frontend URL in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Security scheme for Bearer token
security = HTTPBearer()
# Replace with the URL of your target API endpoint
TARGET_API_URL = os.environ.get("TARGET_API_URL", "https://httpbin.org/anything")
# Configure request timeout from environment variable or default
REQUEST_TIMEOUT_SECONDS = float(
os.getenv("REQUEST_TIMEOUT_SECONDS", 60.0)
) # Default to 60 seconds
request_timeout = Timeout(REQUEST_TIMEOUT_SECONDS)
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""
Verifies the Bearer token exists and is valid.
"""
if credentials.credentials:
return True
else:
raise HTTPException(status_code=401, detail="Invalid token")
async def proxy_api(request: Request):
"""
Proxies the request to the target API endpoint,
changes the original Authorization Bearer header to x-api-key,
and adds a new Authorization Bearer header to the outgoing request.
"""
async with AsyncClient(
timeout=request_timeout
) as client: # Set timeout for AsyncClient
target_url = TARGET_API_URL + request.url.path # Construct target URL
query_params = request.query_params
request_body = await request.body()
headers = dict(request.headers)
# Remove host and connection headers as httpx will handle them
headers.pop("host", None)
headers.pop("connection", None)
original_auth_header = headers.pop(
"authorization", None
) # Get and remove original authorization header
if original_auth_header:
# Extract the token part from "Bearer <token>"
try:
original_token = original_auth_header.split(" ")[1]
headers["x-api-key"] = (
original_token # Add x-api-key header with the original token
)
except IndexError:
# Handle cases where Authorization header is not in "Bearer <token>" format
print(
"Warning: Invalid Authorization header format, not converting to x-api-key."
)
pass # Or you could raise an HTTPException if you want to reject such requests
# Add the new Authorization Bearer header for the target API request
target_api_bearer_token = os.getenv("TARGET_API_BEARER_TOKEN")
if target_api_bearer_token: # check if env var is set before adding header
headers["Authorization"] = f"Bearer {target_api_bearer_token}"
try:
response = await client.request(
request.method,
target_url,
params=query_params,
content=request_body,
headers=headers,
follow_redirects=True, # Handle redirects from target API if needed
)
return Response(
content=response.content,
status_code=response.status_code,
headers=response.headers,
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error communicating with target API: {e}"
)
@app.get("/health")
async def health_check(request: Request):
return await proxy_api(request)
@app.get("/", tags=["Home"])
async def api_home(request: Request):
return await proxy_api(request)
# Define a catch-all path operation to proxy all requests
@app.api_route(
"/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"]
)
async def proxy_endpoint(
path: str, request: Request, token_valid: bool = Depends(verify_token)
):
return await proxy_api(request) # Call proxy_api and return its Response
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|