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 " 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 " 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)