Spaces:
Sleeping
Sleeping
File size: 1,368 Bytes
4ca46dc |
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 |
from fastapi import FastAPI, Request
import httpx
from starlette.responses import RedirectResponse
app = FastAPI()
@app.get("/forward/")
async def forward(request: Request):
# Extract query parameters as a dictionary
query_params = dict(request.query_params)
# Extract the URL to forward to (param1)
forward_url = query_params.pop('param1', None)
# Check if the forward URL is present
if not forward_url:
return {"error": "param1 (forward URL) is required"}
# Prepare the new URL with remaining query parameters
# This assumes that the forward URL does not already have query parameters.
if query_params: # If there are other parameters to forward
params_as_str = "&".join([f"{key}={value}" for key, value in query_params.items()])
forward_url_with_params = f"{forward_url}?{params_as_str}"
else:
forward_url_with_params = forward_url
# Forward the request to the new URL using httpx for asynchronous HTTP requests
async with httpx.AsyncClient() as client:
response = await client.get(forward_url_with_params)
# For simplicity, we're directly returning the response from the forwarded URL
# In a real application, you might want to handle different response scenarios
return response.json()
# To run the server:
# uvicorn app:app --reload
|